Python Lists
Chapter 8
Python for Informatics: Exploring Information
www.pythonlearn.com
[email protected]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' ]
[email protected]
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
[email protected]
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 []
[email protected]
We already use lists!
5
for i in [5, 4, 3, 2, 1] :
4
print (i)
print ('Blastoff!') 3
2
1
Blastoff!
[email protected]
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!
[email protected]
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 >>>
[email protected]
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 = fruit.lower()
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]
[email protected]
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...)
[email protected]
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
[email protected]
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
[email protected]
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
[email protected]
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]
[email protected]
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]
[email protected]
List Methods
>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>>
http://docs.python.org/tutorial/datastructures.html
[email protected]
Building a List from Scratch
• We can create an empty list >>> stuff = list()
and then add elements using >>> stuff.append('book')
the append method >>> stuff.append(99)
>>> print (stuff)
• The list stays in order and ['book', 99]
>>> stuff.append('cookie')
new elements are added at >>> print (stuff)
the end of the list ['book', 99, 'cookie']
[email protected]
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 >>> friends.sort()
>>> 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”
[email protected]
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
[email protected]
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)
numlist.append(value)
average = sum(numlist) / len(numlist)
print ('Average:', average)
[email protected]
Best Friends: Strings and Lists
>>> abc = 'With three words' >>> print (stuff)
>>> stuff = abc.split() ['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.
[email protected]
>>> 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
[email protected]
From [email protected] Sat Jan 5 09:14:16 2008
fhand = open('mbox-short.txt')
Sat
for line in fhand: Fri
line = line.rstrip()
Fri
if not line.startswith('From ') : continue
words = line.split() Fri
print (words[2]) ...
>>> line = 'From [email protected] Sat Jan 5 09:14:16 2008’
>>> words = line.split()
>>> print (words)
['From', '
[email protected]', 'Sat', 'Jan', '5', '09:14:16', '2008']
>>>
[email protected]
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']
[email protected]
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] [email protected]
print pieces[1]
[email protected]
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] [email protected]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]
[email protected]
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] [email protected]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print (pieces[1])
'uct.ac.za'
print pieces[1]
[email protected]
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
[email protected]
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.
Initial Development: Charles Severance, University of Michigan
School of Information
… Insert new Contributors and Translators here
[email protected]