9c. Prof. Rosenthal’s Review#

A review of Chapter 9: Lists, for students who have already studied the chapter. Use the two lists under Concepts covered as a checklist (click a list’s title to hide it), then work through the Questions, which go from easy to hard. Each question has a suggested answer under Answer. Try the question first, then open the Answer.

Run this page on Colab

Concepts covered#

Questions#

The questions use lists, list methods, split and join, sorted, and aliasing. One question reads words.txt, a list of about 114,000 English words, one per line, in alphabetical order (the first two are aa and aah).

The setup cell below downloads words.txt.

from os.path import basename, exists

def download(url):
    filename = basename(url)
    if not exists(filename):
        from urllib.request import urlretrieve

        local, _ = urlretrieve(url, filename)
        print("Downloaded " + str(local))
    return filename

download('https://raw.githubusercontent.com/AllenDowney/ThinkPython/v3/words.txt');

Summary and questions by Prof. Y. Rosenthal, based on Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International

Question 1 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

t = ['spam', 2.0, 5, [10, 20]]
print(len(t), t[0], t[-1])
print(t[3][1], 10 in t, 5 in t)

Question 2 (easy): what is displayed?#

letters = ['a', 'b', 'c', 'd', 'e']
print(letters[1:3], letters[:2], letters[3:])
print([1, 2] + [3], [0] * 3)
print(sum([3, 1, 4]), min([3, 1, 4]), max(['pear', 'apple', 'fig']))

Question 3 (easy): what is displayed?#

t = ['a', 'b', 'c']
t.append('d')
t.extend(['e', 'f'])
print(t)
x = t.pop(1)
t.remove('e')
print(x, t)

Question 4 (easy): what is displayed?#

s = 'pining for the fjords'
words = s.split()
print(words, len(words))
print('-'.join(words))
print(list('abc'), 'ex-parrot'.split('-'))

Question 5 (easy): write a function#

Write a function called squares that takes a non-negative integer n and returns a list of the squares of the integers from 1 to n.

Start from this header (replace ... with the body):

def squares(n):
    ...

Examples

print(squares(4))
[1, 4, 9, 16]
print(squares(1), squares(0))
[1] []

Question 6 (easy): what is displayed?#

t = [[1, 2], [3], []]
for inner in t:
    print(len(inner), sum(inner))
print(len(t))
for x in []:
    print('never')

Question 7 (medium): what is displayed?#

scramble = ['c', 'a', 'b']
result = sorted(scramble)
print(result, scramble)
print(sorted('banana'))
print(''.join(sorted('banana')))
print(sorted([3, 10, 2]), sorted(['3', '10', '2']))

Question 8 (medium): what is displayed?#

a = [1, 2, 3]
b = [1, 2, 3]
c = a
d = a[:]
print(a == b, a is b)
print(a == c, a is c)
print(a == d, a is d)

Question 9 (medium): what is displayed?#

a = [1, 2, 3]
b = a
c = list(a)
b[0] = 5
b.append(4)
c[1] = 7
print(a)
print(b)
print(c)

Question 10 (medium): what is displayed?#

word = 'plumage!'
new_word = word.strip('!')
t = [1, 2, 3]
new_t = t.remove(3)
print(word, new_word)
print(t, new_t)

Question 11 (medium): what happens?#

Each part has one mistake. Predict the error for each, then open the Answer to check.

Part a

t = [1, 2, 3]
t = t.remove(3)
t.remove(2)

Part b

t = ['a', 'b', 'c']
t.remove('d')

Part c

t = ['a', 'b', 'c']
print(t[3])

Part d

t = [1, 2]
t = t + 3

Question 12 (medium): what is displayed?#

def pop_first(lst):
    return lst.pop(0)

letters = ['a', 'b', 'c', 'd']
first = pop_first(letters)
second = pop_first(letters)
print(first, second)
print(letters)

Question 13 (medium): write a function#

Write a function called acronym that takes a string of words separated by spaces and returns a string of the first letters of the words, in uppercase. Strings have an upper method: 'png'.upper() is 'PNG'.

Start from this header (replace ... with the body):

def acronym(phrase):
    ...

Examples

print(acronym('portable network graphics'))
PNG
print(acronym('as soon as possible'), acronym('Python'))
ASAP P

Question 14 (medium): write a function#

Write a function called running_totals that takes a list of numbers and returns a new list in which each element is the sum of the numbers up to and including that position. The function must not change the list it gets.

Start from this header (replace ... with the body):

def running_totals(numbers):
    ...

Examples

print(running_totals([1, 2, 3, 4]))
[1, 3, 6, 10]
print(running_totals([5, -5, 2]), running_totals([]))
[5, 0, 2] []

Question 15 (medium): what is displayed?#

words.txt has one English word per line, in lowercase. Predict what this code displays (you cannot know the number of words, but predict the rest).

word_list = open('words.txt').read().split()
print(len(word_list))
print(word_list[:3], word_list[-1])
print('python' in word_list, 'Python' in word_list)

Question 16 (hard): what is displayed?#

def add_zero(lst):
    lst.append(0)

def add_one(lst):
    lst = lst + [1]

numbers = [5]
add_zero(numbers)
add_one(numbers)
print(numbers)

Question 17 (hard): what is displayed?#

row = [0, 0]
grid = [row, row]
grid[0][1] = 5
print(grid)
print(row)
copies = [row[:], row[:]]
copies[0][0] = 7
print(copies)

Question 18 (hard): write a function#

Write a function called flatten that takes a list of lists and returns a new list with all the elements of the inner lists, in order.

Start from this header (replace ... with the body):

def flatten(nested):
    ...

Examples

print(flatten([[1, 2], [3], [], [4, 5]]))
[1, 2, 3, 4, 5]
print(flatten([['a'], ['b', 'c']]), flatten([]))
['a', 'b', 'c'] []

Question 19 (hard): write a function#

Write a function called remove_all that takes a list t and a value, and removes every element of t that is equal to the value. The function changes the list t and returns None.

Start from this header (replace ... with the body):

def remove_all(t, value):
    ...

Examples

numbers = [1, 1, 2]
remove_all(numbers, 1)
print(numbers)
[2]
letters = ['a', 'b', 'a', 'a']
remove_all(letters, 'a')
print(letters)
['b']

Question 20 (hard): write a function#

Write a function called has_duplicates that takes a list and returns True if any element appears in it more than once, and False otherwise.

Start from this header (replace ... with the body):

def has_duplicates(t):
    ...

Examples

print(has_duplicates([1, 2, 3, 2]), has_duplicates(['a', 'b']))
True False
print(has_duplicates([]), has_duplicates(list('banana')))
False True

Summary and questions by Prof. Y. Rosenthal, based on Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International