Kodeclik Blog
How to unpack a tuple in Python
Tuple unpacking is a process whereby you can extract the contents of a tuple into separate variables. This allows you to access individual elements within the tuple without having to iterate over all the elements.
To understand how to unpack tuples, let us use our tuples to represent books; a book has a name, author, year, and publisher.
Here is code to setup the first book in the Harry Potter series (hence the variable named “HarryPotter1”):
HarryPotter1 = ("Harry Potter and the Philosopher's Stone",
'J.K. Rowling',1997,'Bloomsbury')
print(HarryPotter1)
The output is:
("Harry Potter and the Philosopher's Stone", 'J.K. Rowling',
1997, 'Bloomsbury')
To unpack the tuple into individual variables, we can use two methods as follows.
Method 1: Use the assignment operator
In this approach, we simply use another tuple on the left side of the assignment operator taking care to ensure that the number of variables on the left is of the correct magnitude.
HarryPotter1 = ("Harry Potter and the Philosopher's Stone",
'J.K. Rowling',1997,'Bloomsbury')
(a,b,c,d) = HarryPotter1
print(a)
print(c)
This will unpack the tuple and give you the values in variables a, b, c, and d. We print two of them, giving us the output:
Harry Potter and the Philosopher's Stone
1997
Method 2. Use the destructuring (*) operator
In the second approach, we use the destructuring (*) operator as follows:
HarryPotter1 = ("Harry Potter and the Philosopher's Stone",
'J.K. Rowling',1997,'Bloomsbury')
[*a] = HarryPotter1
print(a)
print(a[0])
This operator is typically used to collect leftover values when performing a destructuring assignment. Thus all the individual tuple elements get organized into a list so that we obtain:
["Harry Potter and the Philosopher's Stone",
'J.K. Rowling', 1997, 'Bloomsbury']
Harry Potter and the Philosopher's Stone
Note that the output is a list followed by the title extracted as the first element of the list.
If you only care about the title, you can do:
HarryPotter1 = ("Harry Potter and the Philosopher's Stone",
'J.K. Rowling',1997,'Bloomsbury')
[t,*a] = HarryPotter1
print(t)
Here the first element deconstructed (the title) goes into variable t and the rest are represented by “*a” (which we do not have any use for). The output is:
Harry Potter and the Philosopher's Stone
In summary, unpacking tuples in Python is a very common need as it allows you to manipulate and process data quickly and efficiently. With the two approaches discussed above you should have no trouble unpacking tuples in your projects. Explore them and tell us how you used them!
If you liked this blogpost, learn about named tuples in Python.
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.