- 5.1 Introduction
- 5.2 Lists
- 5.3 Tuples
- 5.4 Unpacking Sequences
- 5.5 Sequence Slicing
- 5.6 del Statement
- 5.7 Passing Lists to Functions
- 5.8 Sorting Lists
- 5.9 Searching Sequences
- 5.10 Other List Methods
- 5.11 Simulating Stacks with Lists
- 5.12 List Comprehensions
- 5.13 Generator Expressions
- 5.14 Filter, Map and Reduce
- 5.15 Other Sequence Processing Functions
- 5.16 Two-Dimensional Lists
- 5.17 Intro to Data Science: Simulation and Static Visualizations
- 5.18 Wrap-Up
5.4 Unpacking Sequences
The previous chapter introduced tuple unpacking. You can unpack any sequence’s elements by assigning the sequence to a comma-separated list of variables. 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:
In [1]: student_tuple = ('Amanda', [98, 85, 87]) In [2]: first_name, grades = student_tuple In [3]: first_name Out[3]: 'Amanda' In [4]: grades Out[4]: [98, 85, 87]
The following code unpacks a string, a list and a sequence produced by range:
In [5]: first, second = 'hi' In [6]: print(f'{first} {second}') h i In [7]: number1, number2, number3 = [2, 3, 5] In [8]: print(f'{number1} {number2} {number3}') 2 3 5 In [9]: number1, number2, number3 = range(10, 40, 10) In [10]: print(f'{number1} {number2} {number3}') 10 20 30
Swapping Values Via Packing and Unpacking
You can swap two variables’ values using sequence packing and unpacking:
In [11]: number1 = 99 In [12]: number2 = 22 In [13]: number1, number2 = (number2, number1) In [14]: print(f'number1 = {number1}; number2 = {number2}') number1 = 22; number2 = 99
Accessing Indices and Values Safely with Built-in Function enumerate
Earlier, we called range to produce a sequence of index values, then accessed list elements in a for loop using the index values and the subscription operator ([]). This is error-prone because you could pass the wrong arguments to range. If any value produced by range is an out-of-bounds index, using it as an index causes an IndexError.
The preferred mechanism for accessing an element’s index and value is the built-in function enumerate. This function receives an iterable and creates an iterator that, for each element, returns a tuple containing the element’s index and value. The following code uses the built-in function list to create a list containing enumerate’s results:
In [15]: colors = ['red', 'orange', 'yellow'] In [16]: list(enumerate(colors)) Out[16]: [(0, 'red'), (1, 'orange'), (2, 'yellow')]
Similarly the built-in function tuple creates a tuple from a sequence:
In [17]: tuple(enumerate(colors)) Out[17]: ((0, 'red'), (1, 'orange'), (2, 'yellow'))
The following for loop unpacks each tuple returned by enumerate into the variables index and value and displays them:
In [18]: for index, value in enumerate(colors): ...: print(f'{index}: {value}') ...: 0: red 1: orange 2: yellow
Creating a Primitive Bar Chart
The following script creates a primitive bar chart where each bar’s length is made of asterisks (*) and is proportional to the list’s corresponding element value. We use the function enumerate to access the list’s indices and values safely. To run this example, change to this chapter’s ch05 examples folder, then enter:
ipython fig05_01.py
or, if you’re in IPython already, use the command:
run fig05_01.py
1 # fig05_01.py 2 """Displaying a bar chart""" 3 numbers = [19, 3, 15, 7, 11] 4 5 print('\nCreating a bar chart from numbers:') 6 print(f'Index{"Value":>8} Bar') 7 8 for index, value in enumerate(numbers): 9 print(f'{index:>5}{value:>8} {"*" * value}')
The for statement uses enumerate to get each element’s index and value, then displays a formatted line containing the index, the element value and the corresponding bar of asterisks. The expression
"*" * value
creates a string consisting of value asterisks. When used with a sequence, the multiplication operator (*) repeats the sequence—in this case, the string "*"—value times. Later in this chapter, we’ll use the open-source Seaborn and Matplotlib libraries to display a publication--quality bar chart visualization.