Pythonlearn 08 Lists
Pythonlearn 08 Lists
Programming
• Algorithm
1 2
A List is a Kind of
What is Not a “Collection”?
Collection
Most of our variables have one value in them - when we put a new • A collection allows us to put many values in a single “variable”
value in the variable, the old value is overwritten
• A collection is nice because we can carry all many values
around in one convenient package.
$ python
>>> x = 2
>>> x = 4 friends = [ 'Joseph', 'Glenn', 'Sally' ]
>>> print(x)
4 carryon = [ 'socks', 'shirt', 'perfume' ]
3 4
10/01/21
5 6
friends = ['Joseph', 'Glenn', 'Sally'] Just like strings, we can get at any single element in a list using an
for friend in friends :
print('Happy New Year:', friend)
Happy New Year: Joseph index specified in square brackets
print('Done!') Happy New Year: Glenn
Happy New Year: Sally
>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
Done! Joseph Glenn Sally >>> print(friends[1])
z = ['Joseph', 'Glenn', 'Sally'] Glenn
for x in z: 0 1 2 >>>
print('Happy New Year:', x)
print('Done!')
7 8
10/01/21
9 10
11 12
10/01/21
13 14
15 16
10/01/21
17 18
19 20
10/01/21
21 22
words = line.split()
email = words[1]
>>> line = 'From [email protected] Sat Jan 5 09:14:16 2008' print pieces[1]
>>> words = line.split()
>>> print(words)
['From', '[email protected]', 'Sat', 'Jan', '5', '09:14:16', '2008']
>>>
23 24
10/01/21
From [email protected] Sat Jan 5 09:14:16 2008 From [email protected] Sat Jan 5 09:14:16 2008
25 26
27 28
10/01/21
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.
29