For each line of the program, draw the current list as a table and write a short ...
taken from M. Dawson, Python Programming for the Absolute Beginner, 3rd.
Introduction to Python Programming (6) Collections
S. Thater and A. Friedrich Saarland University
Winter Semester 2011/2012
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
1 / 28
List Indices 1 2
myList = ["a", "b", "c", "d", "hello"] myList[3] = "world"
0 "a" -5
1 "b" -4
2 "c" -3
3 "d" -2
4 "hello" -1
What does the following piece of code print out? 1 2 3 4
print(myList[1]) print(myList[4]) print(myList[-2]) print(myList[4][1])
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
2 / 28
Multidimensional Lists 1 2
myList = ["a", "b", [1, 2, 3], "d", "e"] myList[3] = [4, 5, 6] 0 "a"
1 "b"
2 [1, 2, 3]
3 [ 4, 5, 6]
4 "e"
a) What does the following piece of code print out? 1 2
print(myList[1]) print(myList[2][0]) b) How can you access the ’5’? c) What happens in the following cases?
1 2
print(myList[5]) print(myList[2][3])
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
3 / 28
Removing Items from Lists
1 2 3 4 5 6
0 "a"
myList = ["a", "b", "c"] >>> print(myList) ['a', 'b', 'c'] >>> del myList[1] >>> print(myList) ['a', 'c']
1 "b"
S. Thater and A. Friedrich ( Saarland University)
2 "c"
⇒
0 "a"
1 "c"
Introduction to Python Programming
Winter Semester 2011/2012
4 / 28
Appending Items to Lists myList = ["a", "b", "c"]
1 2 3 4 5 6 7 8 9 10
0 "a"
1 "b"
2 "c"
>>> myList = ["a", "b", "c"] >>> myList[3] = "d" Traceback (most recent call last): File "", line 1, in IndexError: list assignment index out of range >>> myList.append("d") >>> print(myList) ['a', 'b', 'c', 'd'] >>> print(myList[3]) d
Lists are mutable (= changeable): items can be changed, added, deleted... S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
5 / 28
More List Functions What are the effects of the following list functions? For each line of the program, draw the current list as a table and write a short documentation explaining what each of the functions does. 1 2 3 4 5 6 7 8 9 10 11 12 13 14
myList = [3, 2, 6, 1, 8] myList.reverse() x = len(myList) myList.sort() myList.insert(2, 5) myList.sort(reverse=True) myList.append(3) myList.count(3) myList.remove(3) x = myList.pop() y = myList.pop() z = 4 in myList myList = myList + [7, 8, 9] del myList[:]
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
6 / 28
Slicing [0] ’a’ [1] ’b’ [2] ’c’ [3] ’d’ [4] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
>>> myList = ['a', 'b', 'c', 'd'] >>> myList[0:3] ['a', 'b', 'c'] >>> myList[2:3] ['c'] >>> myList = ['a', 'b', 'c', 'd'] >>> myList[0:3] ['a', 'b', 'c'] >>> myList[2:4] ['c', 'd'] >>> myList[1:] ['b', 'c', 'd'] >>> myList[:3] ['a', 'b', 'c'] >>> myList[:] ['a', 'b', 'c', 'd']
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
7 / 28
String Immutability Strings are also sequences (of strings: one character at a time) We can access the items of a string: 1 2 3 4 5
>>> myString = "telephone" >>> print(myString[2]) l >>> print(myString[4:]) phone
Strings are immutable sequences ⇒ They can’t change. myString[0] = "T" ⇒ DOES NOT WORK! Concatenation creates new strings.
myString = "T" + myString[1:]
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
8 / 28
Shared References Variables do not contain values (like a tupper box contains food) Variables point to values in the memory, like a name points to a person (the name does not contain the person) 1 2 3 4 5 6 7 8 9
>>> mike = ["khakis", "dress shirt", "jacket"] >>> mr_dawson = mike >>> honey = mike >>> mike ['khakis', 'dress shirt', 'jacket'] >>> mr_dawson ['khakis', 'dress shirt', 'jacket'] >>> honey ['khakis', 'dress shirt', 'jacket']
Examples taken from M. Dawson, Python Programming for the Absolute Beginner, 3rd edition, Course Technology, p.138 S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
9 / 28
Shared References 1 2 3
>>> mike = ["khakis", "dress shirt", "jacket"] >>> mr_dawson = mike >>> honey = mike
1 2 3 4 5
>>> honey[2] = "red sweater" >>> honey ['khakis', 'dress shirt', 'red sweater'] >>> mike ['khakis', 'dress shirt', 'red sweater']
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
10 / 28
Copying a List 1 2
>>> mike = ["khakis", "dress shirt", "jacket"] >>> honey = mike[:]
1 2 3 4 5
>>> honey[2] = "red sweater" >>> honey ['khakis', 'dress shirt', 'red sweater'] >>> mike ['khakis', 'dress shirt', 'jacket']
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
11 / 28
Copying a List Simple case: no nesting. Slicing can be used to copy a list. 1 2 3 4 5 6 7 8
a b a b
= = = =
[1, 2, 3] a[:] ? ?
a[1] = 4 a = ? b = ?
Drawings on board.
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
12 / 28
Shallow Copy of a Nested List
1 2 3 4 5 6 7 8 9
a b a b
= = = =
[1, [2, 3], 5] a[:] ? ?
a[0] = 7 a[1][0] = 8 a = ? b = ?
Drawings on board.
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
13 / 28
Deep Copy of a Nested List
1 2 3 4 5 6 7 8 9
import copy a = [1, [2, 3], 5] b = copy.deepcopy(a) a = ? b = ? a[1][0] = 8 a = ? b = ?
Drawings on board.
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
14 / 28
None
None is Python’s way of representing ’nothing’. Placeholder for any value. Variable does not point anywhere. Can be used for initialization as follows: 1 2 3 4 5 6
x = None while x != "": print("Press Enter to exit.") x = input("Type something to be printed.") if x: print(x)
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
15 / 28
Tuples 1 2 3 4 5 6 7
tom = ("Tom", "Maier", 21, "German") carlos = ("Carlos", "Sanchez", 23, "Spanish") >>> tom[3] = 22 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Tuples are immutable: You cannot change them. I
But: You can create new tuples from existing ones (e.g. concatenation, slicing)
Empty tuples ⇒ False. Advantage VS. lists I I
Tuples are faster than lists Tuples are perfect for creating constants
Tuple with one element: myConstant = (value,) S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
16 / 28
Set unordered, can contain each element at most once may only contain immutable types (numbers, strings, booleans,...) 1 2 3 4 5 6 7 8 9 10
>>> >>> >>> {1, >>> >>> {1, >>> >>> {1,
mySet = {1, 2, 3} mySet = set([1, 2, 3, 3, 4]) mySet 2, 3, 4} mySet.add(5) mySet 2, 3, 4, 5} mySet.remove(2) mySet 3, 4, 5}
What is the effect of set(), how is it applied above? Empty set: set() Careful: {} creates an empty dictionary, not an empty set! S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
17 / 28
frozenset
sets are mutable frozenset works like a set, but all methods that alter the set (inserting, deleting, changing) are prohibited Instantiation: freezing = frozenset(’snow’, ’hail’)
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
18 / 28
Type Conversion of Collections
All collections (except for dictionaries) can be converted into each other. 1 2 3 4 5 6
> a > b > c > d > e ...
= = = = =
set([1,2]) list(a) tuple(a) tuple(b) set(b *5)
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
19 / 28
Dictionaries Access a value using a key (but not vice versa!) A dictionary can’t contain multiple items with the same key.
PHONE BOOK KEY VALUE
Keys have to be immutable (strings, numbers, ...)
Smith Johnson Brown Miller
Values don’t have to be unique. Empty dictionary: phoneBook = dict() or
3253 3938 1443 9388
phoneBook = {} 1 2 3 4 5
>>> phoneBook = {"Smith" : 3253, "Johnson" : 3938, "Brown" : 1443} >>> phoneBook["Smith"] 3253
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
20 / 28
Dictionaries - Check existence of key I
Good style: Check for existence of a key using the in operator: 1 2 3 4 5
person = str(input("Person to look up: ")) if person in phoneBook: print(person, "=", phoneBook[person]) else: print("Sorry, I don't know this person.")
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
21 / 28
Dictionaries - Check existence of key II
... or use the get operator. If no default value is defined and the key does not exist, get returns
None. 1 2 3 4
person = str(input("Person to look up: ")) if person in dictionary: print(person, "=", phoneBook.get(person, "...sorry, no idea"))
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
22 / 28
Dictionaries - Changing Entries
1 2 3 4 5 6 7 8 9
>>> phoneBook {'Brown': 1443, 'Smith': 3253, 'Johnson': 3938} >>> phoneBook['Smith'] = 7777 >>> phoneBook {'Brown': 1443, 'Smith': 7777, 'Johnson': 3938} >>> phoneBook["Miller"] = 9388 >>> phoneBook {'Brown': 1443, 'Smith': 7777, 'Johnson': 3938, 'Miller': 9388}
If key exists, value is overwritten. If key does not exists, new entry is created.
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
23 / 28
Dictionaries - Deleting Entries 1 2 3 4 5 6 7 8 9 10
>>> phoneBook = {'Brown': 1443, 'Smith': 3253, 'Johnson': 3938} >>> del phoneBook["Smith"] >>> phoneBook {'Brown': 1443, 'Johnson': 3938} >>> number = phoneBook.pop("Johnson") >>> phoneBook {'Brown': 1443} >>> number 3938
Check whether a key exists before deleting!
del dict[key] does not return anyting. dict.pop(key) returns the value. S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
24 / 28
Dictionaries - Comparison of Keys
Keys are compared using the == operator. Does it return True? 1 and 1.0 are the same key!
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
25 / 28
Dictionaries - setdefault I get() does never change the dictionary 1 2 3 4 5 6
>>> phoneBook = {'Brown': 1443, 'Smith': 3253, 'Johnson': 3938} >>> phoneBook.get("Miller", 0) 0 >>> phoneBook {'Brown': 1443, 'Smith': 3253, 'Johnson': 3938}
Assume we want to check for a person, and if it doesn’t exist, assign the default phone number 0.
setdefault does the following: 1 2
Checks whether key exists. If yes, returns value. If key does not exists, adds the key with the default value and returns this value. (If none given, default value is None.)
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
26 / 28
Dictionaries - setdefault II
1 2 3 4 5 6 7 8 9 10 11
>>> phoneBook = {'Brown': 1443, 'Smith': 3253, 'Johnson': 3938} >>> phoneBook.setdefault("Smith", 0) 3253 >>> phoneBook {'Brown': 1443, 'Smith': 3253, 'Johnson': 3938} >>> phoneBook.setdefault("Miller", 0) 0 >>> phoneBook {'Brown': 1443, 'Smith': 3253, 'Johnson': 3938, 'Miller': 0}
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
27 / 28
Dictionaries - Views Views show the current state of a dictionary. dict.keys() - returns a view of all the keys of a dictionary. dict.values() - returns a view of all the values of a dictionary. dict.items() - returns a view of all the items in a dictionary. Each item is a tuple: (key, value). Views are like lists, except we can’t change them. Usage: Iterate over views or convert to list. 1 2 3 4 5 6 7 8 9
phoneBook = {'Brown': 1443, 'Smith': 3253} persons = phoneBook.keys() for person in persons: print(person, ">>", phoneBook[person]) entries = phoneBook.items() for entry in entries: print(entry[0], ">>", entry[1])
S. Thater and A. Friedrich ( Saarland University)
Introduction to Python Programming
Winter Semester 2011/2012
28 / 28