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]: ...

Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.