Borislav Hadzhiev
Last updated: Jun 29, 2022
Photo from Unsplash
Unpack the values to split a tuple into multiple variables, e.g.
r, g, b = ('red', 'green', 'blue')
. When unpacking, make sure to declare
exactly as many variables as there are items in the iterable.
r, g, b = ('red', 'green', 'blue') print(r) # 👉️ 'red' print(g) # 👉️ 'green' print(b) # 👉️ 'blue'
When unpacking from a tuple, each variable declaration counts for a single item.
Make sure to declare exactly as many variables as there are items in the tuple.
r, g, b, y = ('red', 'green', 'blue', 'yellow') print(r) # 👉️ 'red' print(g) # 👉️ 'green' print(b) # 👉️ 'blue' print(y) # 👉️ 'yellow'
If you try to unpack more or less values than there are in the tuple, you would get an error.
# ⛔️ ValueError: too many values to unpack (expected 2) r, g = ('red', 'green', 'blue')
ValueError
.If you don't need to store a certain value, use an underscore for the variable's name.
r, _, b = ('red', 'green', 'blue') print(r) # 👉️ 'red' print(b) # 👉️ 'blue'
When you use an underscore for a variable's name, you indicate to other developers that this variable is just a placeholder.
You can use as many underscores as necessary when unpacking values.
r, _, _, y = ('red', 'green', 'blue', 'yellow') print(r) # 👉️ 'red' print(y) # 👉️ 'yellow'
This is needed because it's not valid syntax to have one comma after another.
# ⛔️ SyntaxError: invalid syntax r, , , y = ('red', 'green', 'blue', 'yellow')