0% found this document useful (0 votes)
27 views29 pages

Py4Inf 08 Lists

The document discusses Python lists, including what they are, how to define and manipulate them, common list methods, and how to perform operations on lists such as finding length, maximum/minimum values, sums, and averages.

Uploaded by

junedijoasli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views29 pages

Py4Inf 08 Lists

The document discusses Python lists, including what they are, how to define and manipulate them, common list methods, and how to perform operations on lists such as finding length, maximum/minimum values, sums, and averages.

Uploaded by

junedijoasli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Python Lists

Show a max
loop with a list Chapter 8

Python for Informatics: Exploring Information


www.py4inf.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, 2011, Charles Severance


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' ]


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 over written

$ 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
• List constants are surrounded by >>> print [1, 24, 76]
[1, 24, 76]
square brakets and the elements
in the list are separated by >>> print ['red', 'yellow', 'blue']
commas. ['red', 'yellow', 'blue']
>>> print ['red', 24, 98.6]
• A list element can be any Python ['red', 24, 98.599999999999994]
object - even another list >>> print [ 1, [5, 6], 7]
[1, [5, 6], 7]
• A list can be empty >>> print []
[]
We already use lists!

5
for i in [5, 4, 3, 2, 1] : 4
print i 3
2
print 'Blastoff!' 1
Blastoff!
Lists and definite loops - best pals

friends = ['Joseph', 'Glenn', 'Sally']

for friend in friends : Happy New Year: Joseph


print 'Happy New Year:', friend Happy New Year: Glenn
Happy New Year: Sally
print 'Done!' Done!
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 >>>
Lists are Mutable >>> fruit = 'Bannna'
>>> fruit[0] = 'b'
Traceback
TypeError: 'str' object does not
• Strings are "immutable" - we support item assignment
>>> x = fruit.lower()
cannot change the contents of
a string - we must make a >>> print x
new string to make any bannna
change >>> lotto = [2, 14, 26, 41, 63]
>>> print lotto
• Lists are "mutable" - we can [2, 14, 26, 41, 63]
>>> lotto[2] = 28
change an element of a list
using the index operator >>> print lotto
[2, 14, 28, 41, 63]
How Long is a List?
>>> greet = 'Hello Bob'
• The len() function takes a list as a >>> print len(greet)
9
parameter and returns the
number of elements in the list >>> x = [ 1, 2, 'joe', 99]
>>> print len(x)
• Actually len() tells us the number 4
of elements of any set or sequence >>>
(i.e. such as a string...)
Using the range function
>>> print range(4)
• The range function returns a list [0, 1, 2, 3]
>>> friends = ['Joseph', 'Glenn', 'Sally']
of numbers that range from zero
to one less than the parameter >>> print len(friends)
3
• We can construct an index loop >>> print range(len(friends))
using for and an integer iterator [0, 1, 2]
>>>
A tale of two loops...
>>> friends = ['Joseph', 'Glenn', 'Sally']
>>> print len(friends)
3
friends = ['Joseph', 'Glenn', 'Sally']
>>> print range(len(friends))
for friend in friends : [0, 1, 2]
>>>
print 'Happy New Year:', friend

for i in range(len(friends)) :
print 'Happy New Year:', friends[i] Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Concatenating lists using +

>>> 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 = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c'] Remember: Just like in
>>> t[:4] strings, the second number
['a', 'b', 'c', 'd'] is "up to but not
>>> t[3:] including"
['d', 'e', 'f']
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
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()


• We can create an empty >>> stuff.append('book')
list and then add elements >>> stuff.append('ipod')
using the append method >>> print stuff
['book', 'ipod']
• The list stays in order and
>>> stuff.append('cookie')
new elements are added at
the end of the list >>> print stuff
['book', 'ipod', 'cookie']
Is Something in a List?
• Python provides two
>>> some = [1, 9, 21, 10, 16]
operators that let you
check if an item is in a list >>> 9 in some
True
• These are logical >>> 15 in some
operators that return True False
or False >>> 20 not in some
True
• They do not modify the >>>
list
A List is an Ordered Sequence
• A list can hold many items
>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
and keeps those items in the
>>> friends.sort()
order until we do something
>>> print friends
to change the order
['Glenn', 'Joseph', 'Sally']
• A list can be sorted (i.e. >>> print friends[2]
Sally
change its order)
>>>
• The sort method (unlike in
strings) means "sort yourself"
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
74
parameters
>>> print min(nums)
3
• Remember the loops we
>>> print sum(nums)
built? These are much
simpler 154
>>> print sum(nums)/len(nums)
25
http://docs.python.org/lib/built-in-funcs.html
total = 0 Enter a number: 3
count = 0 Enter a number: 9
while ( True ) : Enter a number: 5
inp = raw_input('Enter a number: ') Enter a number: done
if inp == 'done' : break Average: 5.66666666667
value = float(inp)
total = total + value
count = count + 1 numlist = list()
while ( True ) :
average = total / count inp = raw_input('Enter a number: ')
print 'Average:', average if inp == 'done' : break
value = float(inp)
numlist.append(value)
Averaging
average = sum(numlist) / len(numlist)
with a list print 'Average:', average
Best Friends: Strings and Lists
>>> print stuff
>>> abc = 'With three words' ['With', 'three', 'words']
>>> stuff = abc.split() >>> for w in stuff :
>>> print stuff ... print w
['With', 'three', 'words'] ...
>>> print len(stuff) With
3 three
>>> print stuff[0] words
With >>>

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() When you do not specify a
>>> print thing delimiter, multiple spaces are
['first#second#third'] treated like “one” delimiter.
>>> print len(thing)
1 You can specify what delimiter
>>> thing = line.split('#')
>>> print thing character to use in the splitting.
['first', 'second', 'third']
>>> print len(thing)
3
>>>
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
Fri
words = line.split()
...
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']
>>>
The Double Split
• Sometimes we split a line one way and then grab one of the pieces of
the line and split that piece again

From [email protected] Sat 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
• Sometimes we split a line one way and then grab one of the pieces of
the line and split that piece again

From [email protected] Sat Jan 5 09:14:16 2008

words = line.split() stephen.marquard uct.ac.za


[email protected]
email = words[1]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]
'uct.ac.za'
The Double Split
• Sometimes we split a line one way and then grab one of the pieces of
the line and split that piece again

From [email protected] Sat Jan 5 09:14:16 2008

words = line.split() [email protected]


email = words[1]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za'
'uct.ac.za']
print pieces[1]
The Double Split
• Sometimes we split a line one way and then grab one of the pieces of
the line and split that piece again

From [email protected] Sat Jan 5 09:14:16 2008

words = line.split() [email protected]


email = words[1]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]
'uct.ac.za'
Mystery Problem...
From [email protected] Sat Jan 5 09:14:16 2008

fhand = open('mbox-short.txt')
for line in fhand: Sat
line = line.rstrip() Traceback (most recent call last):
words = line.split() File "search8.py", line 5, in <module>
if words[0] != 'From' : continue if words[0] != 'From' : continue
print words[2] IndexError: list index out of range
List Summary
• Concept of a collection • List methods: append, remove
• Lists and definite loops • Sorting lists
• Indexing and lookup • Splitting strings into lists of
words
• List mutability
• Using split to parse strings
• Functions: len, min, max, sum
• Slicing lists

You might also like