Unpacking tuples in Python

Tuples are a special type of container object in Python that can be used to hold values. The act of assigning it these values is called “packing”. The reverse of this is called unpacking, which we can use to extract values from tuples into regular python variables.


How to unpack tuples in Python

The below code demonstrates a simple example where we unpack a tuple contained three values into three individual variables.

# Packing Values into a tuple
mytuple = ("Green", "Blue", "Yellow")

# Unpacking from a tuple
x1, x2, x3 = mytuple

print(x1)
print(x2)
print(x3)
Green
Blue
Yellow

Make sure the number of variables match the number of values inside the tuple, otherwise an error will be raised.


If our tuple is very large, creating alot of variables for it can be rather tiring. Or it could be that we want only to unpack a certain portion of the tuple into a list (such as the first two values, or all values except the first two).

For these purposes, we can add an asterisk * , before a variable. With this operator we no longer need to match the number of arguments to the number of values in the tuple.

# Packing Values into a tuple
mytuple = ("Green", "Blue", "Brown", "Red", "Yellow")

# Unpacking from a tuple
x1, *x2, x3 = mytuple
print(x1)
print(x2)
print(x3)

It is important to note that only one variable amongst the unpacked variables can have the asterisk (*) on it. If not present, this will create ambiguity and will raise an error.

Did you know that unpacking works on lists too?


Unpack a Tuple into a Function

Another cool thing we can do is unpack tuples when passing them into functions. If a function has two parameters, and our tuple has two values, we can have the tuple directly unpack itself into those two parameters.

Here is an example:

def concat(x, y):
    print( x + " " + y )

# Packing Values into a list
mytuple = ["Good", "Morning"]

# Unpacking from a list
concat(*mytuple)
Good Morning

Just in case you didn’t notice it, you need to include a little asterisk before the tuple in the function call.


Did you know? Unpacking also works on list objects too!


This marks the end of the Unpacking tuples in Python Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments