Open In App

Unpacking a Tuple in Python

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Tuple unpacking is a powerful feature in Python that allows you to assign the values of a tuple to multiple variables in a single line. This technique makes your code more readable and efficient. In other words, It is a process where we extract values from a tuple and assign them to variables in a single step. This feature makes working with tuples more convenient and readable.

Tuple unpacking allows assigning values from a tuple directly to variables:

Python
a, b, c = (100, 200, 300)

print(a)  
print(b)  
print(c)  

Output
100
200
300

Key Rules:

  • The number of variables on the left must match the number of elements in the tuple.
  • If they do not match, Python raises a ValueError.
  • Example: a, b = (100, 200, 300) # ValueError: too many values to unpack

Tuple Unpacking Techniques

1. Using _ for Unused Values

If we don’t need certain values, use _ as a throwaway variable or placeholder:

Python
a, _, c = (100, 200, 300)
print(a)  
print(c)  

Output
100
300

2. Using * for Variable-Length Unpacking

Python allows catching multiple elements using *, known as the extended unpacking technique:

Python
a, *b = (1, 2, 3, 4, 5)
print(a)   
print(b)   

Output
1
[2, 3, 4, 5]

3. Unpacking Nested Tuples

Tuples inside tuples can also be unpacked:

Python
nested_tuple = (1, (2, 3), 4)
a, (b, c), d = nested_tuple

print(a)   
print(b)   
print(c)   
print(d)   

Output
1
2
3
4

4. Tuple Unpacking with * in Function Arguments

a. using *args: When defining a function, *args allows passing multiple arguments as a tuple:

Python
def add(*args):
    return sum(args)

print(add(1, 2, 3, 4))  

Output
10

b. Using * for Argument Unpacking: Tuple unpacking can also be used when calling a function:

Python
def add(a, b, c):
    return a + b + c

nums = (1, 2, 3)
print(add(*nums))  

Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy