0% found this document useful (0 votes)
40 views28 pages

Python Lists: Python For Informatics: Exploring Information

The document discusses Python lists, including what they are, how to define and access elements of lists, common list methods like append and len, slicing lists, checking for elements in lists, and sorting lists. It also covers using lists with functions like max, min, sum, and average.

Uploaded by

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

Python Lists: Python For Informatics: Exploring Information

The document discusses Python lists, including what they are, how to define and access elements of lists, common list methods like append and len, slicing lists, checking for elements in lists, and sorting lists. It also covers using lists with functions like max, min, sum, and average.

Uploaded by

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

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
• 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
>>> 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, 98.599999999999994]
object - even another list
>>> 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
print i
2
print 'Blastoff!'
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 N
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 = 'Banana’
>>> fruit[0] = 'b’
Traceback
TypeError: 'str' object does not
• Strings are "immutable" - we support item assignment
cannot change the contents of >>> x = fruit.lower()
a string - we must make a new >>> print x
string to make any change banana
>>> lotto = [2, 14, 26, 41, 63]
• Lists are "mutable" - we can
>>> print lotto[2, 14, 26, 41, 63]
change an element of a list
>>> lotto[2] = 28
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)
parameter and returns the number 9
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]
of numbers that range from zero >>> friends = ['Joseph', 'Glenn', 'Sally']
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)
friends = ['Joseph', 'Glenn', 'Sally'] 3
>>> print range(len(friends))
for friend in friends : [0, 1, 2]
print 'Happy New Year:', friend >>>

for i in range(len(friends)) :
friend = friends[i] Happy New Year: Joseph
print 'Happy New Year:', friend 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 = [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

>>> stuff = list()


• We can create an empty list >>> stuff.append('book')
and then add elements >>> stuff.append(99)
using the append method >>> print stuff
['book', 99]
• The list stays in order and
>>> stuff.append('cookie')
new elements are added at
the end of the list >>> print stuff
['book', 99, 'cookie']
Is Something in a List?

• Python provides two >>> some = [1, 9, 21, 10, 16]


>>> 9 in some
operators that let you
check if an item is in a list True
>>> 15 in some
• These are logical operators False
that return True 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
and keeps those items in the >>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
order until we do something >>> friends.sort()
to change the order >>> print friends
['Glenn', 'Joseph', 'Sally']
• A list can be sorted (i.e.
>>> print friends[1]
change its order)
Joseph>>>
• The sort method (unlike in
strings) means "sort yourself"
Built in Functions and Lists
>>> nums = [3, 41, 12, 9, 74, 15]
• There are a number of >>> print len(nums)
functions built into Python 6
that take lists as >>> print max(nums)
parameters 74>>> print min(nums)
3
• Remember the loops we >>> print sum(nums)
built? These are much 154
simpler >>> print sum(nums)/len(nums)
25
http://docs.python.org/lib/built-in-funcs.html
Enter a number: 3
total = 0
count = 0 Enter a number: 9
while True : Enter a number: 5
inp = raw_input('Enter a number: ')
if inp == 'done' : break Enter a number: done
value = float(inp) Average: 5.66666666667
total = total + value
count = count + 1

average = total / count


print 'Average:', average
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
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 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.
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 Pattern
• 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


[email protected]

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

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 Pattern
• 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 Pattern
• 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'
List Summary

You might also like