Chap08python Lists
Chap08python Lists
Chapter 8
A List is a kind of
Collection
• A collection allows us to put many values in a single “variable”
$ 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]
• List constants are surrounded by [1, 24, 76]
square brakets 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,
object - even another list 98.599999999999994]
>>> print [ 1, [5, 6], 7]
• A list can be empty [1, [5, 6], 7]
>>> print []
[]
We already use lists!
5
4
for i in [5, 4, 3, 2, 1]
3
:
2
print i
1
print 'Blastoff!'
Blastoff
!
Lists and definite loops - best pals
• Just like strings, we can get at any single element in a list using an
index specified in square brackets
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
• We can create a new list by adding
>>> print c
two exsiting lists together
[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] Remember: Just like in
>>> t[:4] strings, the second number
[9, 41, 12, 3] is "up to but not including"
>>> t[3:]
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]
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
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.
fhand = open('mbox-short.txt')
Sat
for line in fhand:
Fri
line = line.rstrip()
Fri
if not line.startswith('From ') : continue
Fri
words = line.split()
...
print words[2]
From [email protected]
[email protected] Jan 5 09:14:16 2008
words = line.split()
email = words[1]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]
'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