2.3.2. Unpack Iterables#

2.3.2.1. Clean Iterables Unpacking in Python#

Are you extracting items from an iterable using indexing?

l = [1, 2, 3]

a = l[0]
b = l[1]
c = l[2]

A more efficient way to achieve the same result is to assign the iterable to multiple variables simultaneously.

l = [1, 2, 3]
a, b, c = l
print("a =", a)
print("b =", b)
print("c =", c)
a = 1
b = 2
c = 3

This can make our code easier to read and understand, and is a common practice in Python.

2.3.2.2. Extended Iterable Unpacking: Ignore Multiple Values when Unpacking a Python Iterable#

If we have a longer iterable but we only want to extract the subset of the iterable, we can use the “splat” operator (*) to represent the elements that we don’t care about:

a, *_, b = [1, 2, 3, 4]
print("a =", a)
print("b =", b)
print("_ =", _)
a = 1
b = 4
_ = [2, 3]