5 | Sequences: Lists and Tuples (Self Check)
append, pop
(Fill-In) You can simulate a stack with a list, using methods _____ and _____ to add and remove elements, respectively, only at the end of the list.
Filter, map, reduce
(Fill-In) _____, _____ and _____ are common operations used in functional-style programming.
In [1]: numbers = [67, 12, 46, 43, 13] In [2]: numbers.index(43) Out[2]: 3 In [3]: if 44 in numbers: ...: print(f'Found 44 at index: {numbers.index(44)}') ...: else: ...: print('44 not found') ...: 44 not found
(IPython Session) Create a five-element list containing 67, 12, 46, 43 and 13, then use list method index to search for a 43 and 44. Ensure that no ValueError occurs when searching for 44.
In [1]: foods = ['Cookies', 'pizza', 'Grapes', ...: 'apples', 'steak', 'Bacon'] ...: In [2]: foods.sort( ) In [3]: foods Out[3]: ['Bacon', 'Cookies', 'Grapes', 'apples', 'pizza', 'steak']
(IPython Session) Create a foods list containing 'Cookies', 'pizza', 'Grapes', 'apples', 'steak' and 'Bacon'. Use list method sort to sort the list in ascending order. Are the strings in alphabetical order?
In [1]: def cube_list(values): ...: for i in range(len(values)): ...: values[i] **= 3 ...: In [2]: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [3]: cube_list(numbers) In [4]: numbers Out[4]: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
(IPython Session) Create a function cube_list that cubes each element of a list. Call the function with the list numbers containing 1 through 10. Show numbers after the call.
*=
(Fill-In) The _____ operator can be used to extend a list with copies of itself.
extend
(Fill-In) To add all the elements of a sequence to the end of a list, use list method _____, which is equivalent to using +=.
reverse
(Fill-In) To sort a list in descending order, call list method sort with the optional keyword argument __________ set to True.
Axes
(Fill-In) A Matplotlib _____ object manages the content that appears in a Matplotlib window.
lazy
(Fill-In) A generator expression is _____—it produces values on demand.
if
(Fill-In) A list comprehension's _____ clause filters sequence elements to select only those that match a condition.
for
(Fill-In) A list comprehension's _____ clause iterates over the specified sequence.
unpacked
(Fill-In) A sequence's elements can be _____ by assigning the sequence to a comma-separated list of variables.
reduction
(Fill-In) A(n) _____ processes a sequence's elements into a single value, such as their count, total or average.
names[::-1]
(Fill-In) Assume you have a list called names. The slice expression _____ creates a new list with the elements of names in reverse order.
reversed
(Fill-In) Built-in function ___________ returns an iterator that enables you to iterate over a sequence's values backward.
clear
(Fill-In) For a list numbers, calling method _____ is equivalent to numbers[:] = [].
9
(Fill-In) Given a list numbers containing 1 through 10, del numbers[-2] removes the value _____ from the list.
row, column
(Fill-In) In a two-dimensional list, the first index by convention identifies the _____ of an element and the second index identifies the _____ of an element.
in, not in
(Fill-In) Operators _____ and _____ determine whether a sequence contains or does not contain a value, respectively.
immutable
(Fill-In) Python's string and tuple sequences are _____—they cannot be modified.
show
(Fill-In) The Matplotlib function _____ displays a plot window from a script.
barplot
(Fill-In) The Seaborn function _____ displays data as a bar chart.
the list's length is greater than 0.
(Fill-In) To prevent an IndexError when calling pop on a list, first ensure that ____________________________________.
comma (,)
(Fill-In) The _____ format specifier indicates that a number should be displayed with thousands separators.
In [1]: list(x ** 3 for x in [10, 3, 7, 1, 9, 4, 2] if x % 2 == 0) Out[1]: [1000, 64, 8]
(IPython Session) Create a generator expression that cubes the even integers in a list containing 10, 3, 7, 1, 9, 4 and 2. Use function list to create a list of the results. Note that the function call's parentheses also act as the generator expression's parentheses.
In [1]: numbers = list(range(1, 16)) In [2]: numbers Out[2]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] In [3]: list(filter(lambda x: x % 2 == 0, numbers)) Out[3]: [2, 4, 6, 8, 10, 12, 14] In [4]: list(map(lambda x: x ** 2, numbers)) Out[4]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225] In [5]: list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers))) Out[5]: [4, 16, 36, 64, 100, 144, 196]
(IPython Session) Create a list called numbers containing 1 through 15, then perform the following tasks: 1. Use the built-in function filter with a lambda to select only numbers' even elements. Create a new list containing the result. 2. Use the built-in function map with a lambda to square the values of numbers' elements. Create a new list containing the result. 3. Filter numbers' even elements, then map them to their squares. Create a new list containing the result.
In [1]: numbers = list(range(1, 16)) In [2]: numbers Out[2]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] In [3]: numbers[1:len(numbers):2] Out[3]: [2, 4, 6, 8, 10, 12, 14] In [4]: numbers[5:10] = [0] * len(numbers[5:10]) In [5]: numbers Out[5]: [1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 11, 12, 13, 14, 15] In [6]: numbers[5:] = [] In [7]: numbers Out[7]: [1, 2, 3, 4, 5] In [8]: numbers[:] = [] In [9]: numbers Out[9]: []
(IPython Session) Create a list called numbers containing the values from 1 through 15, then use slices to perform the following operations consecutively: 1. Select number's even integers. 2. Replace the elements at indices 5 through 9 with 0s, then show the resulting list. 3. Keep only the first five elements, then show the resulting list. 4. Delete all the remaining elements by assigning to a slice. Show the resulting list.
In [1]: numbers = list(range(1, 16)) In [2]: numbers Out[2]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] In [3]: del numbers[0:4] In [4]: numbers Out[4]: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] In [5]: del numbers[::2] In [6]: numbers Out[6]: [6, 8, 10, 12, 14]
(IPython Session) Create a list called numbers containing the values from 1 through 15, then use the del statement to perform the following operations consecutively: 1. Delete a slice containing the first four elements, then show the resulting list. 2. Starting with the first element, use a slice to delete every other element of the list, then show the resulting list.
In [1]: rainbow = ['green', 'orange', 'violet'] In [2]: rainbow.insert(rainbow.index('violet'), 'red') In [3]: rainbow Out[3]: ['green', 'orange', 'red', 'violet'] In [4]: rainbow.append('yellow') In [5]: rainbowOut[5]: ['green', 'orange', 'red', 'violet', 'yellow'] In [6]: rainbow.reverse() In [7]: rainbow Out[7]: ['yellow', 'violet', 'red', 'orange', 'green'] In [8]: rainbow.remove('orange') In [9]: rainbow Out[9]: ['yellow', 'violet', 'red', 'green']
(IPython Session) Create a list called rainbow containing 'green', 'orange' and 'violet'. Perform the following operations consecutively using list methods and show the list's contents after each operation: 1. Determine the index of 'violet', then use it to insert 'red' before 'violet'. 2. Append 'yellow' to the end of the list. 3. Reverse the list's elements. 4. Remove the element 'orange'.
In [1]: single = (123.45,) In [2]: single Out[2]: (123.45,)
(IPython Session) Create a single-element tuple containing 123.45, then display it.
In [1]: high_low = ('Monday', 87, 65) In [2]: high_low Out[2]: ('Monday', 87, 65) In [3]: print(f'{high_low[0]}: High={high_low[1]}, Low={high_low[2]}')Monday: High=87, Low=65In [4]: day, high = high_low -------------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-3-0c3ad5c97284> in <module>() ----> 1 day, high = high_low ValueError: too many values to unpack (expected 2)
(IPython Session) Create a tuple high_low representing a day of the week (a string) and its high and low temperatures (integers), display its string representation, then perform the following tasks in an interactive IPython session:Use the [] operator to access and display the high_low tuple's elements. 1. Unpack the high_low tuple into the variables day and high. 2. What happens and why?
The min result was different because 'apples' is the smallest string when you compare them without case sensitivity. In [1]: foods = ['Cookies', 'pizza', 'Grapes', ...: 'apples', 'steak', 'Bacon'] ...: In [2]: min(foods) Out[2]: 'Bacon' In [3]: min(foods, key=lambda s: s.lower()) Out[3]: 'apples'
(IPython Session) Create the list foods containing 'Cookies', 'pizza', 'Grapes', 'apples', 'steak' and 'Bacon'. Find the smallest string with min, then reimplement the min call using the key function to ignore the strings' case. Do you get the same results? Why or why not?
In [4]: names = ['Amanda', 'Sam', 'David'] In [5]: for i, name in enumerate(names): ...: print(f'{i}: {name}') ...: 0: Amanda 1: Sam 2: David
(IPython Session) Create the list names containing three name strings. Use a for loop and the enumerate function to iterate through the elements and display each element's index and value.
In [6]: fahrenheit = [41, 32, 212] In [7]: list(map(lambda x: (x, (x - 32) * 5 / 9), fahrenheit)) Out[7]: [(41, 5.0), (32, 0.0), (212, 100.0)]
(IPython Session) Map a list of the three Fahrenheit temperatures 41, 32 and 212 to a list of tuples containing the Fahrenheit temperatures and their Celsius equivalents. Convert Fahrenheit temperatures to Celsius with the following formula: Celsius = (Fahrenheit - 32) * (5 / 9)
In [3]: [1, 2, 3] + (4, 5, 6) -------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-3-1ac3d3041bfa> in <module>() ----> 1 [1, 2, 3] + (4, 5, 6) TypeError: can only concatenate list (not "tuple") to list
(IPython Session) Show what happens when you attempt to concatenate sequences of different types—the list [1, 2, 3] and the tuple (4, 5, 6)—using the + operator.
In [3]: multiples = [x for x in range(3, 30, 3)] In [4]: multiples Out[4]: [3, 6, 9, 12, 15, 18, 21, 24, 27]
(IPython Session) Use a list comprehension and the range function with a step to create a list of the multiples of 3 that are less than 30.
In [1]: cubes = [(x, x ** 3) for x in range(1, 6)] In [2]: cubes Out[2]: [(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
(IPython Session) Use a list comprehension to create a list of tuples containing the numbers 1-5 and their cubes—that is, [(1, 1), (2, 8), (3, 27), ...]. To create tuples, place parentheses around the expression to the left of the list comprehension's for clause.
In [5]: characters = [] In [6]: characters += 'Birthday' In [7]: characters Out[7]: ['B', 'i', 'r', 't', 'h', 'd', 'a', 'y']
(IPython Session) Use an empty list named characters and a += augmented assignment statement to convert the string 'Birthday' into a list of its characters.
In [20]: plt.cla() In [21]: %recall 5 In [22]: rolls = [random.randrange(1, 7) for i in range(6000000)] In [23]: %recall 6-13 In [24]: values, frequencies = np.unique(rolls, return_counts=True) ...: title = f'Rolling a Six-Sided Die {len(rolls):,} Times' ...: sns.set_style('whitegrid') ...: axes = sns.barplot(values, frequencies, palette='bright') ...: axes.set_title(title) ...: axes.set(xlabel='Die Value', ylabel='Frequency') ...: axes.set_ylim(top=max(frequencies) * 1.10) ...: for bar, frequency in zip(axes.patches, frequencies): ...: text_x = bar.get_x() + bar.get_width() / 2.0 ...: text_y = bar.get_height() ...: text = f'{frequency:,}\n{frequency / len(rolls):.3%}' ...: axes.text(text_x, text_y, text, ...: fontsize=11, ha='center', va='bottom') ...:
(IPython Session) Use the %recall magic to repeat the steps in snippets [14] through [18] to redraw the bar plot for 6,000,000 die rolls. This exercise assumes that you're continuing this section's IPython session. Notice that the heights of the six bars look the same, although each frequency is close to 1,000,000 and each percentage is close to 16.667%.
In [4]: [(a + b) for a, b in zip([10, 20, 30], [1, 2, 3])] Out[4]: [11, 22, 33]
(IPython Session) Use zip with two integer lists to create a new list containing the sum of the elements from corresponding indices in both lists (that is, add the elements at index 0, add the elements at index 1, ...).
sales[0][0], sales[0][1], sales[0][2], sales[1][0], sales[1][1], sales[1][1]
(Label the Elements) Label the elements of the two-by-three list sales to indicate the order in which they're set to zero by the following program segment: for row in range(len(sales)): for col in range(len(sales[row])): sales[row][col] = 0
False. A += augmented assignment statement also may be used with strings and tuples, even though they're immutable. The result is a new string or tuple, respectively.
(True/False) A += augmented assignment statement may not be used with strings and tuples, because they're immutable.
False. Immutable sequences like tuples and strings do not provide a sort method. However, you can sort any sequence without modifying it by using built-in function sorted, which returns a new list containing the sorted elements of its argument sequence.
(True/False) All sequences provide a sort method.
False. Slice operations that do not modify a sequence work identically for lists, tuples and strings.
(True/False) Slice operations that modify a sequence work identically for lists, tuples and strings.
False. The + operator's operand sequences must have the same type; otherwise, a TypeError occurs.
(True/False) The + operator's sequence operands may be of any sequence type.
False: In this context, the multiplication operator (*) repeats the string ('-') 10 times.
(True/False) The following expression causes an error: '-' * 10
False. Strings are compared by their characters' underlying numerical values. Lowercase letters have higher numerical values than uppercase. So, the comparison is True.
(True/False) The letter 'V' "comes after" the letter 'g' in the alphabet, so the comparison 'Violet' < 'green' yields False.
True
(True/False) Tuples can contain lists and other mutable objects. Those mutable objects can be modified when a tuple is passed to a function.
False. Even though a tuple is immutable, its elements can be mutable objects, such as lists.
(True/False) Tuples can contain only immutable objects.
False. When you pass a list (a mutable object) to a function, the function receives a reference to the original list object and can use that reference to modify the original list's contents.
(True/False) You cannot modify a list's contents when you pass it to a function.
1. 2. 2. 3. 3. 6. 4. t[1][0], t[1][1], t[1][2]. 5. t[0][2], t[1][2]. 6. t[0][1] = 10. 7. for row in range(len(t)): for column in range(len(t[row])): t[row][column] = row + column
(Two-Dimensional Array) Consider a two-by-three integer list t. 1. How many rows does t have? 2. How many columns does t have? 3. How many elements does t have? 4. What are the names of the elements in row 1? 5. What are the names of the elements in column 2? 6. Set the element in row 0 and column 1 to 10. 7. Write a nested for statement that sets each element to the sum of its indices.
In [1]: t = [[10, 7, 3], [20, 4, 17]] In [2]: total = 0 In [3]: items = 0 In [4]: for row in t: ...: for item in row: ...: total += item ...: items += 1 ...: In [5]: total / items Out[5]: 10.166666666666666 In [6]: total = 0 In [7]: items = 0 In [8]: for row in t: ...: total += sum(row) ...: items += len(row) ...: In [9]: total / items Out[9]: 10.166666666666666
t = [[10, 7, 3], [20, 4, 17]] 1. Determine and display the average of t's elements using nested for statements to iterate through the elements. 2. Write a for statement that determines and displays the average of t's elements using the reductions sum and len to calculate the sum of each row's elements and the number of elements in each row.