Split a tuple into multiple variables in Python

avatar

Borislav Hadzhiev

Last updated: Jun 29, 2022

banner

Photo from Unsplash

Split a tuple into multiple variables in Python #

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.

main.py
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.

main.py
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.

main.py
# ⛔️ ValueError: too many values to unpack (expected 2) r, g = ('red', 'green', 'blue')
We declare 2 variables, but the tuple contains 3 items. The inconsistency between the number of variables and items in the tuple causes a ValueError.

If you don't need to store a certain value, use an underscore for the variable's name.

main.py
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.

main.py
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.

main.py
# ⛔️ SyntaxError: invalid syntax r, , , y = ('red', 'green', 'blue', 'yellow')
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.