Python Lists
Chapter 8
Python for Informatics: Exploring Information
www.pythonlearn.com
Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License.
http://creativecommons.org/licenses/by/3.0/.
Copyright 2010- Charles Severance
A List is a kind of Collection
friends = [ 'Joseph', 'Glenn', 'Sally' ]
carryon = [ 'socks', 'shirt', 'perfume' ]
What is not a “Collection”
$ 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
>>> print [1, 24, 76]
[1, 24, 76]
>>> print ['red', 'yellow', 'blue']
['red', 'yellow', 'blue']
>>> print ['red', 24, 98.6]
['red', 24, 98.599999999999994]
>>> print [ 1, [5, 6], 7]
[1, [5, 6], 7]
>>> print []
[]
We already use lists!
for i in [5, 4, 3, 2, 1] :
print i
print 'Blastoff!'
5
4
3
2
1
Blastoff!
Lists and definite loops - best pals
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print 'Happy New Year:', friend
print 'Done!'
Happy New Year: JosephHappy New Year: GlennHappy New Year: SallyDone!
Looking Inside Lists
0
Joseph
>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
>>> print friends[1]
Glenn
>>>
1
Glenn
2
Sally
Lists are Mutable
>>> fruit = 'Banana’
>>> fruit[0] = 'b’
Traceback
TypeError: 'str' object does not
support item assignment
>>> x = fruit.lower()
>>> print x
banana
>>> lotto = [2, 14, 26, 41, 63]
>>> print lotto[2, 14, 26, 41, 63]
>>> lotto[2] = 28
>>> print lotto
[2, 14, 28, 41, 63]
How Long is a List?
>>> greet = 'Hello Bob’
>>> print len(greet)
9
>>> x = [ 1, 2, 'joe', 99]
>>> print len(x)
4
>>>
Using the range function
>>> print range(4)
[0, 1, 2, 3]
>>> friends = ['Joseph', 'Glenn', 'Sally']
>>> print len(friends)
3
>>> print range(len(friends))
[0, 1, 2]
>>>
A tale of two loops...
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print 'Happy New Year:', friend
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
>>> friends = ['Joseph', 'Glenn', 'Sally']
>>> print len(friends)
3
>>> print range(len(friends))
[0, 1, 2]
>>>
Concatenating lists using +
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
>>> print a
[1, 2, 3]
Lists can be sliced using :
>>> t = [9, 41, 12, 3, 74, 15]
>>> t[1:3]
[41,12]
>>> t[:4]
[9, 41, 12, 3]
>>> t[3:]
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]
Remember: Just like in strings, the second number is "up to but not including"
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
Building a list from scratch
>>> stuff = list()
>>> stuff.append('book')
>>> stuff.append(99)
>>> print stuff
['book', 99]
>>> stuff.append('cookie')
>>> print stuff
['book', 99, 'cookie']
Is Something in a List?
>>> some = [1, 9, 21, 10, 16]
>>> 9 in some
True
>>> 15 in some
False
>>> 20 not in some
True
>>>
A List is an Ordered Sequence
>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
>>> friends.sort()
>>> print friends
['Glenn', 'Joseph', 'Sally']
>>> print friends[1]
Joseph>>>
Built in Functions and Lists
>>> nums = [3, 41, 12, 9, 74, 15]
>>> print len(nums)
6
>>> print max(nums)
74>>> print min(nums)
3
>>> print sum(nums)
154
>>> print sum(nums)/len(nums)
25
http://docs.python.org/lib/built-in-funcs.html
numlist = list()
while True :
inp = raw_input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print 'Average:', average
total = 0
count = 0
while True :
inp = raw_input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
total = total + value
count = count + 1
average = total / count
print 'Average:', average
Enter a number: 3
Enter a number: 9
Enter a number: 5
Enter a number: done
Average: 5.66666666667
Best Friends: Strings and Lists
>>> abc = 'With three words’
>>> stuff = abc.split()
>>> print stuff
['With', 'three', 'words']
>>> print len(stuff)
3
>>> print stuff[0]
With
>>> print stuff
['With', 'three', 'words']
>>> for w in stuff :
... print w
...
With
Three
Words
>>>
Split breaks a string into parts 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.
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From ') : continue
words = line.split()
print words[2]
Sat
Fri
Fri
Fri
...
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
>>> line = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008’
>>> words = line.split()
>>> print words
['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008']
>>>
The Double Split Pattern
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
words = line.split()
email = words[1]
pieces = email.split('@')
print pieces[1]
stephen.marquard@uct.ac.za
['stephen.marquard', 'uct.ac.za']
'uct.ac.za'
The Double Split Pattern
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
words = line.split()
email = words[1]
pieces = email.split('@')
print pieces[1]
stephen.marquard@uct.ac.za
['stephen.marquard', 'uct.ac.za']
'uct.ac.za'
stephen.marquard
uct.ac.za
The Double Split Pattern
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
words = line.split()
email = words[1]
pieces = email.split('@')
print pieces[1]
stephen.marquard@uct.ac.za
['stephen.marquard', 'uct.ac.za']
'uct.ac.za'
The Double Split Pattern
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
words = line.split()
email = words[1]
pieces = email.split('@')
print pieces[1]
stephen.marquard@uct.ac.za
['stephen.marquard', 'uct.ac.za']
'uct.ac.za'
List Summary