Professional Documents
Culture Documents
WIN SEM (2020-21) CSE0101 ETH AP2020215000188 Reference Material I 06-Apr-2021 Module-4 Lists
WIN SEM (2020-21) CSE0101 ETH AP2020215000188 Reference Material I 06-Apr-2021 Module-4 Lists
$ python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
>>> x = 2
>>> x = 4
>>> print x
4
List Constants
5
for i in [5, 4, 3, 2, 1] :
print i
4
print 'Blastoff!' 3
2
1
Blastoff!
Lists and definite loops - best pals
Split breaks a string into parts and produces a list of strings. We think of these
as words. We can access a particular word or loop through all the words.
>>> line = 'A lot of spaces'
>>> etc = line.split()
>>> print etc
['A', 'lot', 'of', 'spaces']
>>>
>>> line = 'first;second;third'
>>> thing = line.split()
>>> print thing
['first;second;third']
>>> print len(thing)
1
>>> thing = line.split(';')
>>> print thing
['first', 'second', 'third']
>>> print len(thing)
3
>>>
● When you do not specify a delimiter, multiple spaces are treated like one delimiter
● You can specify what delimiter character to use in the splitting
The Double Split Pattern
• Sometimes we split a line one way, and then grab one of the pieces
of the line and split that piece again
words = line.split()
email = words[1]
print pieces[1]
['stephen.marquard', 'uct.ac.za']
The Double Split Pattern
• Sometimes we split a line one way, and then grab one of the pieces
of the line and split that piece again
words = line.split()
email = words[1] stephen.marquard@uct.ac.za
print pieces[1]
The Double Split Pattern
• Sometimes we split a line one way, and then grab one of the pieces
of the line and split that piece again
words = line.split()
email = words[1] stephen.marquard@uct.ac.za
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]
The Double Split Pattern
• Sometimes we split a line one way, and then grab one of the pieces
of the line and split that piece again
words = line.split()
email = words[1] stephen.marquard@uct.ac.za
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]
'uct.ac.za'
print pieces[1]
List Summary
• Slicing lists
• Concept of a collection
• List methods: append, remove
• Lists and definite loops
• Sorting lists
• Indexing and lookup
• Splitting strings into lists of words
• List mutability
• Using split to parse strings
• Functions: len, min, max, sum