Chapter 5, Sequences: Lists and Tuples 1
Sequences: Lists and Tuples
5.1 Introduction
5.1 Q1: Which of the following statements is false?
a. Collections are prepackaged data structures consisting of related data items.
b. Examples of collections include your favorite songs on your smartphone, your
contacts list, a library’s books, your cards in a card game, your favorite sports
team’s players, the stocks in an investment portfolio, patients in a cancer study
and a shopping list.
c. Lists are modifiable and tuples are not. Each can hold items of the same or dif-
ferent types.
d. Tuples can dynamically resize as necessary, growing and shrinking at execution
time.
5.2 Lists
5.2 Q1: Lists may store ________ data, that is, data of many different types.
a. parallel
b. heterogeneous
c. homogeneous
d. None of the above.
5.2 Q2: Consider the list c:
c = [–45, 6, 0, 72, 1543]
Which of the following statements a), b) or c) is false?
a. You reference a list element by writing the list’s name followed by the element’s
index (that is, its position number) enclosed in square brackets ([], known as the
subscription operator).
b. The names of c’s elements are c[0], c[1], c[2], c[3] and c[4].
c. The length of c is 5.
d. All of the above statements are true.
5.2 Q3: Which of the following statements is false?
2 Chapter 5, Sequences: Lists and Tuples
a. Lists are mutable—their elements can be modified.
b. You can insert and delete list elements, changing the list’s length.
c. You can get the individual characters in a string, and you can assign a new value
to one of the string’s characters.
d. Python’s string and tuple sequences are immutable—they cannot be modified.
5.2 Q4: Which of the following statements a), b) or c) is false?
a. You can concatenate two lists, two tuples or two strings using the + operator.
The result is a new sequence of the same type containing the left operand’s ele-
ments followed by the right operand’s elements.
b. A TypeError occurs if the + operator’s operands are different sequence
types—for example, concatenating a list and a tuple is an error.
c. List elements can be accessed via their indices and the subscription operator
([]).
d. All of the above statements are true.
5.2 Q5: a. We’ve replaced the results of the four list comparisons in snippets [4]
through [7] below with ???. What are those four values?
In [1]: a = [1, 2, 3]
In [2]: b = [1, 2, 3]
In [3]: c = [1, 2, 3, 4]
In [4]: a == b
Out[4]: ???
In [5]: a == c
Out[5]: ???
In [6]: a < c
Out[6]: ???
In [7]: c >= b
Out[7]: ???
a. False, True, False, False.
b. True, False, False, True.
Chapter 5, Sequences: Lists and Tuples 3
c. True, False, True, True.
d. True, True, True, False.
5.3 Tuples
5.3 Q1: Which of the following statements is false?
a. Tuples are immutable.
b. Tuples must store heterogeneous data (that is, data of different types).
c. A tuple’s length is its number of elements.
d. A tuple’s length cannot change during program execution.
5.3 Q2: Which of the following statements is false?
a. You can pack a tuple by separating its values with commas.
b. When you output a tuple, Python always displays its contents in parentheses.
c. You may surround a tuple’s comma-separated list of values with optional pa-
rentheses.
d. The following statement creates a one-element tuple:
a_singleton_tuple = (‘red’)
5.2 Q3: Which of the following statements is false?
a. Usually, you iterate over a tuple’s elements.
b. Like list indices, tuple indices start at 0.
c. The following snippets create a time_tuple representing an hour, minute and
second, display the tuple, then use its elements to calculate the number of seconds
since midnight:
In [1]: time_tuple = (9, 16, 1)
In [2]: time_tuple
Out[2]: (9, 16, 1)
In [3]: time_tuple[0] * 3600 + time_tuple[1] * 60 +
time_tuple[2]
Out[3]: 33361
d. Assigning a value to a tuple element causes a TypeError.
4 Chapter 5, Sequences: Lists and Tuples
© Copyright 2020 by Pearson Education, Inc. All Rights Reserved.
Answer: a. Actually, though a tuple is a sequence, usually you do not iterate
over a tuple’s elements; rather, you access each individually. Usually, you
iterate over a list’s elements.
5.3 Q4: Which of the following statements is false?
a. The += augmented assignment statement can be used with strings and tuples,
even though they’re immutable.
b. In the following snippets, after the two assignments, tuple1 and tuple2 are
two different copies of the same tuple object:
In [1]: tuple1 = (10, 20, 30)
In [2]: tuple2 = tuple1
In [3]: tuple2
Out[3]: (10, 20, 30)
c. Concatenating the tuple (40, 50) to tuple1 from Part (b), as in
tuple1 += (40, 50)
creates a new tuple, then assigns a reference to it to the variable tuple1—tuple2
still refers to the original tuple.
d. For a string or tuple, the item to the right of += must be a string or tuple, re-
spectively—mixing types causes a TypeError.
5.3 Q5: Which of the following statements a), b) or c) is false?
a. The following code creates a student_tuple with a first name, last name and
list of grades:
student_tuple = (‘Amanda’, ‘Blue’, [98, 75, 87])
b. Even though the tuple in Part (a) is immutable, its list element is mutable.
c. In the expression student_tuple[2][1], Python views student_tuple[2]
as the element of the tuple containing the list [98, 75, 87], then uses [1] to ac-
cess the list element containing 75.
d. All of the above statements are true.
5.4 Unpacking Sequences
5.4 Q1: Which of the following statements a), b) or c) is false?
Chapter 5, Sequences: Lists and Tuples 5
a. You can unpack any sequence’s elements by assigning the sequence to a
comma-separated list of variables.
b. A ValueError occurs if the number of variables to the left of the assignment
symbol is not identical to the number of elements in the sequence on the right.
c. The following code unpacks a sequence produced by range:
number1, number2, number3 = range(3)
d. All of the above statements are true.
5.4 Q2: Which of the following statements a), b) or c) is false?
a. The preferred mechanism for accessing an element’s index and value is the
built-in function enumerate, which receives an iterable and creates an iterator
that, for each element, returns a tuple containing the element’s index and value.
b. The following code uses the built-in function list to create a list of tuples con-
taining enumerate’s results:
colors = [‘red’, ‘orange’, ‘yellow’]
colors_list = list(enumerate(colors))
c. The following for loop unpacks each tuple returned by enumerate into the
variables index and value and displays them:
for index, value in enumerate(colors):
print(f‘{index}: {value}‘)
d. All of the above statements are true.
5.5 Sequence Slicing
5.5 Q1: Which of the following statements is false?
a. You can slice sequences to create new sequences of the same type containing
subsets of the original elements.
b. Slice operations can modify mutable sequences. Slice operations that do not
modify a sequence work identically for lists, tuples and strings.
c. The following code creates a slice consisting of the elements at indices 2
through 6 of the list numbers:
numbers = [2, 3, 5, 7, 11, 13, 17, 19]
numbers2 = numbers[2:6]
d. When taking a slice of a list, the original list is not modified.
8 Chapter 5, Sequences: Lists and Tuples
for i in range(len(items)):
items[i] *= 2
b. Part (a)’s function modify_elements’ items parameter receives a reference
to the original list, so the statement in the loop’s suite modifies each element in
the original list object.
c. When you pass a tuple to a function, attempting to modify the tuple’s immutable
elements results in a TypeError.
d. Tuples may contain mutable objects, such as lists, but those objects cannot be
modified when a tuple is passed to a function.
5.8 Sorting Lists
5.8 Q1: Which of the following statements a), b) or c) is false?
a. You can use list method sort as follows to arrange a list’s elements in ascend-
ing order:
numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
numbers.sort()
b. To sort a list in descending order, call list method sort with the optional key-
word argument reverse=False.
c. Built-in function sorted returns a new list containing the sorted elements of
its argument sequence—the original sequence is unmodified.
d. All of the above statements are true.
5.9 Searching Sequences
5.9 Q1: Which of the following statements is false?
a. Often, you’ll want to determine whether a sequence (such as a list, tuple or
string) contains a value that matches a particular key value.
b. Searching is the process of locating a key in a sequence.
c. List method index takes as an argument a search key—the value to locate in
the list—then searches through the list from index 1 and returns the index of the
first element that matches the search key.
d. List method index raises a ValueError if the value you’re searching for is not
in the list.
10 Chapter 5, Sequences: Lists and Tuples
d. Functions any and all are examples of external iteration in functional-style
programming.
5.10 Other List Methods
5.10 Q1: Consider the list color_names:
color_names = [‘orange’, ‘yellow’, ‘green’]
Which of the following statements a), b) or c) is false?
a. Lists also have methods that add and remove elements.
b. Method insert adds a new item at a specified index. The following inserts
‘red’ at index 0:
color_names.insert(0, ‘red’)
c. You can add a new item to the end of a list with method append.
d. All of the above statements are true.
5.10 Q2: Which of the following statements is false?
a. List method remove deletes the first element with a specified value—a
NameError occurs if remove’s argument is not in the list.
b. List method count searches for its argument in a list and returns the number
of times it is found.
c. List method reverse reverses the contents of a list in place.
d. List method copy returns a new list containing a shallow copy of the original
list.
5.11 Simulating Stacks with Lists
5.11 Q1: Which of the following statements is false?
a. Python does not have a built-in stack type, but you can think of a stack as a
constrained list.
b. You push using list method append, which adds a new element to the end of
the list.
c. You pop using list method pop with no arguments, which removes and returns
the item at the front of the list.
d. You can run out of memory if you keep pushing items faster than you pop them.
Chapter 5, Sequences: Lists and Tuples 11
© Copyright 2020 by Pearson Education, Inc. All Rights Reserved.
Answer: c. Actually, you pop using list method pop with no arguments, which
removes and returns the item at the end of the list.
5.12 List Comprehensions
5.12 Q1: Which of the following statements a), b) or c) is false?
a. List comprehensions provide a concise and convenient notation for creating
new lists.
b. List comprehensions can replace many for statements that iterate over exist-
ing sequences and create new lists, such as:
list1 = []
for item in range(1, 6):
list1.append(item)
We can accomplish the same task in a single line of code with a list comprehen-
sion:
list2 = [item for item in range(1, 6)]
c. The list comprehension’s for clause in Part (b) iterates over the sequence pro–
duced by range(1, 6). For each item, the list comprehension evaluates the ex-
pression to the left of the for clause and places the expression’s value (in this
case, the item itself) in the new list.
d. All of the above statements are true.
5.12 Q2: Which of the following statements a), b) or c) is false?
a. A list comprehension’s expression can perform tasks, such as calculations, that
map elements to new values (possibly of different types).
b. Mapping is a common functional-style programming operation that produces
a result with more elements than the original data being mapped.
c. The following list comprehension uses the expression item ** 3 to map each
value in a range to the value’s cube:
list3 = [item ** 3 for item in range(1, 6)]
d. All of the above statements are true.
5.12 Q3: Which of the following statements is false?.
12 Chapter 5, Sequences: Lists and Tuples
a. A common functional-style programming operation is filtering elements to se-
lect only those that match a condition.
b. Filtering typically produces a list with more elements than the data being fil-
tered.
c. To do filtering in a list comprehension, use the if clause.
d The following list comprehension includes in list4 only the even values pro-
duced by the for clause:
list4 = [item for item in range(1, 11) if item % 2 == 0]
5.13 Generator Expressions
5.13 Q1: Which of the following statements a), b) or c) is false?
a. A generator expression is similar to a list comprehension, but is enclosed in
parentheses (rather than []) and creates an iterable generator object that pro-
duces values on demand.
b. The generator expression in the following for statement squares and returns
only the odd values in numbers:
numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
for value in (x ** 2 for x in numbers if x % 2 != 0):
print(value, end=‘ ‘)
c. A generator expression does not create a list.
d. All of the above statements are true.
5.14 Filter, Map and Reduce
5.14 Q1: Which of the following statements is false?
a. The following code uses built-in function filter to obtain the odd values in
numbers:
numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
def is_odd(x):
“””Returns True only if x is odd.”””
return x % 2 != 0
list(filter(is_odd, numbers))
Chapter 5, Sequences: Lists and Tuples 13
b. Python functions are objects that you can assign to variables, pass to other func-
tions and return from functions.
c. Function filter’s first argument must be a function that receives one argu-
ment and returns True if the value should be included in the result.
d. Function filter returns an iterator, so filter’s results are produced imme-
diately.
5.14 Q2: Which of the following statements is false?
a. For simple functions that return only a single expression’s value, you can use a
lambda expression to define the function inline where it’s needed—typically as
it’s passed to another function.
b. A lambda expression is an anonymous function—that is, a function without a
name.
c. In the following filter call the first argument is the lambda:
filter(lambda x: x % 2 != 0, numbers)
d. A lambda explicitly returns its expression’s value.
5.14 Q3: Which of the following statements is false?
a. The following code uses built-in function map with a lambda to square each
value in numbers:
list(map(lambda x: x ** 2, numbers))
b. Function map’s first argument is a function that receives one value and returns
a new value—in Part (a), a lambda that squares its argument. Function map’s sec-
ond argument is an iterable of values to map.
c. Function map uses eager evaluation.
d. The equivalent list comprehension to Part (a) is:
[item ** 2 for item in numbers]
5.14 Q4: Which of the following statements is false?
a. Reductions process a sequence’s elements into a small number of values.
b. The built-in functions len, sum, min and max perform reductions.
14 Chapter 5, Sequences: Lists and Tuples
c. You also can create custom reductions using the functools module’s reduce
function.
d. In the worlds of big data and Hadoop, MapReduce programming is based on the
filter, map and reduce operations in functional-style programming.
5.15 Other Sequence Processing Functions
5.15 Q1: Which of the following statements a), b) or c) is false?
a. Sometimes you’ll need to find the minimum and maximum of more complex
objects, such as strings.
b. Consider the following comparison:
‘Red’ < ‘orange’
The letter ‘R’ “comes after” ‘o’ in the alphabet, so ‘Red’ is greater than
‘orange’ and the condition above is False.
c. Built-in function ord returns the numerical value of a character.
d. All of the above statements are true.
5.16 Two-Dimensional Lists
5.16 Q1: Which of the following statements a), b) or c) is false?
a. Lists can contain other lists as elements.
b. To identify a particular table element, we specify two indices—by convention,
the first identifies the element’s column, the second the element’s row.
c. Multidimensional lists can have more than two indices.
d. All of the above statements are true.
5.16 Q2: Consider a two-dimensional list with three rows and four columns (i.e.,
a 3-by-4 list) that might represent the grades of three students who each took
four exams in a course:
a = [[77, 68, 86, 73], [96, 87, 89, 81], [70, 90, 86, 81]]
Which of the following statements a), b) or c) is false?
a. Writing the list as follows makes its row and column tabular structure clearer:
Chapter 5, Sequences: Lists and Tuples 15
a = [77, 68, 86, 73], # first student’s grades
[96, 87, 89, 81], # second student’s grades
[70, 90, 86, 81] # third student’s grades
b. The element names in the last column all have 3 as the second index.
c. The following nested for statement outputs the rows of the two-dimensional
list a one row at a time:
for row in a:
for item in row:
print(item, end=‘ ‘)
print()
d. All of the above statements are true.
5.17 Intro to Data Science: Simulation and Static
Visualizations
5.17 Q1: Which of the following statements a), b) or c) is false?
a. Visualizations help you “get to know” your data.
b. Visualizations give you a powerful way to understand data that goes beyond
simply looking at raw data.
c. The Matplotlib visualization library is built over the Seaborn visualization li-
brary and simplifies many Seaborn operations.
d. All of the above statements are true.
5.17 Q2: Which of the following statements is false?
a. Seaborn refers to the following type of graph as a bar plot:
16 Chapter 5, Sequences: Lists and Tuples
b. For 600 die rolls, we expect about 100 occurrences of each die face. As we run
a die-rolling simulation for 60,000 die rolls, the bars will become much closer in
size. At 6,000,000 die rolls, they’ll appear to be exactly the same size. This is the
“principal of least privilege” at work.
c. For 6,000,000 rolls, we expect about 1,000,000 of each face.
d. The larger the number of die rolls, the closer the frequency percentages will be
to the expected 16.667%.
5.17.2 Visualizing Die-Roll Frequencies and Percentages
5.17 Q3: Which of the following statements a), b) or c) is false?
a. The following code uses a list comprehension to create a list of 600 random die
values, then uses NumPy’s unique function to determine the unique roll values
(guaranteed to include all six possible face values) and their frequencies:
rolls = [random.randrange(1, 7) for i in range(600)]
values, frequencies = np.unique(rolls, return_counts=True)
b. The NumPy library provides the high-performance ndarray collection, which
is typically much faster than lists.
c. Specifying the keyword argument return_counts=True tells unique to count
each unique value’s number of occurrences.
d. All of the above statements are true.