Python tuple unpack: What do underscores and asterisks mean in unpacking?
You can get all items of a tuple without the for or while statement.
s = ('a', 'b', 'c') x, y, z = s print(x) # a print(y) # b print(z) # c
This style is called "unpack" in Python.
x is the first element of
y is the second element. To unpack a tuple, the number of variables must be the same as the tuple length. Here is incorrect.
s = ('a', 'b', 'c') x, y, z, w = s # ValueError: not enough values to unpack (expected 4, got 3)
Unpack a tuple with a trailing comma
Even though a tuple has a trailing comma, the number of unpacked variables is the same as the number of elements in a tuple.
a, b, c = (1, 2, 3,) print(a) # 1 print(b) # 2 print(c) # 3
The below is incorrect.
a, b, c, d = (1, 2, 3,) # ValueError: not enough values to unpack (expected 4, got 3)
Get only some values
If you want the second value ("b") and don't need other values, use the underscores to unpack needless values.
s = ('a', 'b', 'c') _, y, _ = s print(y) # b
The first and last values are assigned to underscores and "b" is assigned to "y". Surprisingly,
_ has the unpacked value.
a, _, _ = (1, 2, 3) print(_) # 3
The underscores has been assigned to 2 and then 3 in the above example. So the underscore is 3. The underscore means you will never use the unpacked values so you should not basically use it to save or get access to the elements of a tuple.
Unpack a tuple that has only one element
s = (1) t = (5,) print(type(s)) # <class 'int'> print(type(t)) # <class 'tuple'> a = t b, = t print(a) # (5,) print(b) # 5
First of all, one value in tuple-like brackets without trailing comma is not a tuple.
(1) is simply 1. When unpacking a one-element tuple, a comma is needed.
Unpack as list
x, *y = (1, 2, 3, 4) print(x) # 1 print(y) # [2, 3, 4]
The variable with asterisk gets all the item except "named" values. This unpacking is called Extended Iterable Unpacking (in PEP 3132).
x, *y, z = (1, 2, 3, 4) print(x) # 1 print(y) # [2, 3] print(z) # 4
Note: Unpack a string
a, b = 'ER' print(a) # E print(b) # R
A string can be unpacked. The number of values to unpack must be equal to the length of string.
a, b = 'PHP' # ValueError: too many values to unpack (expected 2)
But using Extended Iterable Unpacking, the value with asterisk get all the "unnamed" letters.
a, *b = 'Python' print(a) # P print(b) # ['y', 't', 'h', 'o', 'n']
The way to split a string is explained in Python string split and splitlines.