 • Print
This chapter is from the book

## 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 : student_tuple = ('Amanda',   [98, 85, 87])

In : first_name, grades = student_tuple

In : first_name
Out: 'Amanda'

Out: [98, 85, 87]```

The following code unpacks a string, a list and a sequence produced by range:

```In : first, second = 'hi'

In : print(f'{first}    {second}')
h  i

In : number1, number2, number3 = [2,   3, 5]

In : print(f'{number1}    {number2}  {number3}')
2  3  5

In : number1, number2, number3 = range(10, 40, 10)

In : 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 : number1 = 99

In : number2 = 22

In : number1, number2 = (number2, number1)

In : 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 : colors = ['red', 'orange', 'yellow']

In : list(enumerate(colors))
Out: [(0, 'red'), (1, 'orange'), (2, 'yellow')]```

Similarly the built-in function tuple creates a tuple from a sequence:

```In : tuple(enumerate(colors))
Out: ((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 : 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.