2.3.3. Unpack Iterables¶
2.3.3.1. How to Unpack Iterables in Python¶
To assign items of a Python iterables (such as list, tuple, string) to different variables, you can unpack the iterable like below.
nested_arr = [[1, 2, 3], ["a", "b"], 4]
num_arr, char_arr, num = nested_arr
num_arr
[1, 2, 3]
char_arr
['a', 'b']
2.3.3.2. Extended Iterable Unpacking: Ignore Multiple Values when Unpacking a Python Iterable¶
If you want to ignore multiple values when unpacking a Python iterable, add *
to _
as shown below.
This is called “Extended Iterable Unpacking” and is available in Python 3.x.
a, *_, b = [1, 2, 3, 4]
print(a)
1
b
4
_
[2, 3]