Exercises for Lesson 20
Exercise 1: list
operations
We’ve seen some list operations before. Let’s explore a few more.
Predict the values of numbers
and words
after executing each of the following statements. Assume that numbers
and words
are reset to their original values before each statement.
numbers = [3, 1, 4, 1, 5]
words = ["apple", "banana", "cat", "dog", "elephant"]
a) "apple" in words
b) "nana" in words
c) numbers.remove(2)
d) numbers.sort()
e) words.sort(reverse=True)
f) numbers.append([words.index("cat")])
g) words.pop(numbers.pop(3))
h) words.insert(numbers[0], "fish")
Exercise 2: Dictionaries
Let’s play around with Python dict
objects.
Part a: getting values from a dict
Predict the value of each expression.
charMap = {'a': 'b', 'b': 'c', 'c': 'd'}
silly = {"apple": 4,
314: "111",
(3, 2): [1,2,3,10],
"zebra": {'a': 1, 'b': 3, 'c': 4},
"func": int}
p = (3,2)
ch = 'b'
a) charMap[ch]
b) charMap['d']
c) silly["apple"] * silly[314]
d) silly[1]
e) silly[p][-1]
f) silly["zebra"]
g) silly["zebra"][charMap[ch]]
h) silly["func"](silly[314]) + 100
Part b: updating a dict
Predict the values of charMap
and silly
after executing each of the following statements. Assume that charMap
and silly
are reset to their original values before each statement.
charMap = {'a': 'b', 'b': 'c', 'c': 'd'}
silly = {"apple": 4,
314: "111",
(3, 2): [1,2,3,10],
"zebra": {'a': 1, 'b': 3, 'c': 4},
"func": int}
n = 314
ch = 'e'
a) charMap[ch] = 'z'
b) charMap['a'] = 'y'
c) silly[(3,2)].append(33)
d) charMap['a'] += silly[n]
e) silly["func"] = -4
f) silly["zebra"][charMap['b']] = 5