Python Lists
Chapter 8
Python for Informatics: Exploring Information
[Link]
reachus@[Link]
A List is a kind of Collection
• A collection allows us to put many values in a single “variable”
• A collection is nice because we can carry all many values around in
one convenient package.
friends = [ 'Joseph', 'Glenn', 'Sally' ]
carryon = [ 'socks', 'shirt', 'perfume' ]
reachus@[Link]
What is not a “Collection”
Most of our variables have one value in them - when we put a new
value in the variable, the old value is overwritten
$ 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
reachus@[Link]
List Constants
>>> print [1, 24, 76]
• List constants are surrounded by [1, 24, 76]
square brackets and the elements in >>> print (['red', 'yellow',
'blue'])
the list are separated by commas ['red', 'yellow', 'blue']
>>> print (['red', 24, 98.6])
• A list element can be any Python ['red', 24, 98.599999999999994]
>>> print ([ 1, [5, 6], 7])
object - even another list [1, [5, 6], 7]
>>> print ([])
• A list can be empty []
reachus@[Link]
We already use lists!
5
for i in [5, 4, 3, 2, 1] :
4
print (i)
print ('Blastoff!') 3
2
1
Blastoff!
reachus@[Link]
Lists and definite loops - best pals
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends : Happy New Year: Joseph
print ('Happy New Year:', friend)
print ('Done!') Happy New Year: Glenn
Happy New Year: Sally
Done!
reachus@[Link]
Looking Inside Lists
Just like strings, we can get at any single element in a list using an
index specified in square brackets
>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
Joseph Glenn Sally >>> print (friends[1])
Glenn
0 1 2 >>>
reachus@[Link]
Lists are Mutable
>>> fruit = 'Banana'
>>> fruit[0] = 'b'
• Strings are “immutable” - we Traceback
cannot change the contents of a TypeError: 'str' object does not
support item assignment
string - we must make a new >>> x = [Link]()
string to make any change >>> print (x)
banana
>>> lotto = [2, 14, 26, 41, 63]
• Lists are “mutable’ - we can >>> print (lotto)
change an element of a list [2, 14, 26, 41, 63]
>>> lotto[2] = 28
using the index operator >>> print (lotto)
[2, 14, 28, 41, 63]
reachus@[Link]
How Long is a List?
• The len() function takes a list as a >>> greet = 'Hello Bob'
parameter and returns the number >>> print (len(greet))
of elements in the list 9
>>> x = [ 1, 2, 'joe', 99]
>>> print (len(x))
• Actually len() tells us the number of
4
elements of any set or sequence >>>
(such as a string...)
reachus@[Link]
Using the range function
• The range function returns a
range object. When the object is >>> print (range(4))
converted to a list it results in a range(0, 4)
>>> friends = ['Joseph', 'Glenn', 'Sally']
list of numbers ranging from 0 >>> print (len(friends))
to 1 less than the parameter. 3
>>> print (range(len(friends)))
range(0, 3)
• We can construct an index loop >>>
using for and an integer iterator
reachus@[Link]
Is Something in a List?
• Python provides two >>> some = [1, 9, 21, 10, 16]
operators that let you check >>> 9 in some
True
if an item is in a list
>>> 15 in some
False
• These are logical operators >>> 20 not in some
that return True or False True
>>>
• They do not modify the list
reachus@[Link]
A tale of two loops...
>>> friends = ['Joseph', 'Glenn', 'Sally']
friends = ['Joseph', 'Glenn', 'Sally'] >>> print (len(friends))
3
for friend in friends : >>> print (list(range(len(friends))))
print ('Happy New Year:', friend) [0, 1, 2]
>>>
for i in range(len(friends)) :
friend = friends[i]
print ('Happy New Year:', friend) Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
reachus@[Link]
Concatenating lists using +
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
• We can create a new list by adding
>>> c = a + b
two existing lists together >>> print (c)
[1, 2, 3, 4, 5, 6]
>>> print (a)
[1, 2, 3]
reachus@[Link]
Lists can be sliced using :
>>> t = [9, 41, 12, 3, 74, 15]
>>> t[1:3]
[41,12] Remember: Just like in
>>> t[:4]
[9, 41, 12, 3]
strings, the second number
>>> t[3:] is “up to but not including”
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]
reachus@[Link]
List Methods
>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>>
[Link]
reachus@[Link]
Building a List from Scratch
• We can create an empty list >>> stuff = list()
and then add elements using >>> [Link]('book')
the append method >>> [Link](99)
>>> print (stuff)
• The list stays in order and ['book', 99]
>>> [Link]('cookie')
new elements are added at >>> print (stuff)
the end of the list ['book', 99, 'cookie']
reachus@[Link]
A List is an Ordered Sequence
• A list can hold many items and
keeps those items in the order >>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
until we do something to >>> [Link]()
>>> print (friends)
change the order ['Glenn', 'Joseph', 'Sally']
>>> print (friends[1])
• A list can be sorted Joseph
(i.e., change its order) >>>
• The sort method (unlike in
strings) means “sort yourself”
reachus@[Link]
Built-in Functions and Lists
>>> nums = [3, 41, 12, 9, 74, 15]
>>> print (len(nums))
• There are a number of 6
functions built into Python >>> print (max(nums))
that take lists as parameters 74
>>> print (min(nums))
• Remember the loops we 3
built? These are much >>> print (sum(nums))
simpler. 154
>>> print (sum(nums)/len(nums))
25
reachus@[Link]
total = 0
count = 0
Enter a number: 3
while True : Enter a number: 9
inp = input('Enter a number: ')
if inp == 'done' : break Enter a number: 5
value = float(inp)
total = total + value Enter a number: done
count = count + 1 Average: 5.66666666667
average = total / count
print ('Average:', average)
numlist = list()
while True :
inp = input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
[Link](value)
average = sum(numlist) / len(numlist)
print ('Average:', average)
reachus@[Link]
Best Friends: Strings and Lists
>>> abc = 'With three words' >>> print (stuff)
>>> stuff = [Link]() ['With', 'three', 'words']
>>> print (stuff) >>> for w in stuff :
['With', 'three', 'words'] ... print (w)
>>> print (len(stuff)) ...
3 With
>>> print (stuff[0]) Three
With Words
>>>
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.
reachus@[Link]
>>> line = 'A lot of spaces'
>>> etc = [Link]()
>>> print (etc)
['A', 'lot', 'of', 'spaces']
>>>
>>> line = 'first;second;third'
>>> thing = [Link]()
>>> print (thing)
['first;second;third']
>>> print (len(thing))
1
>>> thing = [Link](';')
>>> 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
reachus@[Link]
From [Link]@[Link] Sat Jan 5 09:14:16 2008
fhand = open('[Link]')
Sat
for line in fhand: Fri
line = [Link]()
Fri
if not [Link]('From ') : continue
words = [Link]() Fri
print (words[2]) ...
>>> line = 'From [Link]@[Link] Sat Jan 5 09:14:16 2008’
>>> words = [Link]()
>>> print (words)
['From', '[Link]@[Link]', 'Sat', 'Jan', '5', '09:14:16', '2008']
>>>
reachus@[Link]
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
From [Link]@[Link] Sat Jan 5 09:14:16 2008
words = [Link]()
email = words[1]
print pieces[1]
['[Link]', '[Link]']
reachus@[Link]
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
From [Link]@[Link] Sat Jan 5 09:14:16 2008
words = [Link]()
email = words[1] [Link]@[Link]
print pieces[1]
reachus@[Link]
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
From [Link]@[Link] Sat Jan 5 09:14:16 2008
words = [Link]()
email = words[1] [Link]@[Link]
pieces = [Link]('@') ['[Link]', '[Link]']
print pieces[1]
reachus@[Link]
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
From [Link]@[Link] Sat Jan 5 09:14:16 2008
words = [Link]()
email = words[1] [Link]@[Link]
pieces = [Link]('@') ['[Link]', '[Link]']
print (pieces[1])
'[Link]'
print pieces[1]
reachus@[Link]
List Summary
• Concept of a collection • Slicing lists
• Lists and definite loops • List methods: append, remove
• Indexing and lookup • Sorting lists
• List mutability • Splitting strings into lists of words
• Functions: len, min, max, sum • Using split to parse strings
reachus@[Link]
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
...
([Link]) of the University of Michigan School of
Information and [Link] 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.
Initial Development: Charles Severance, University of Michigan
School of Information
… Insert new Contributors and Translators here
reachus@[Link]