Unpacking a Tuple in Python (original) (raw)

Last Updated : 18 Feb, 2025

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)

`

Key Rules:

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)

`

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)

`

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)

`

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))

`

**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))

`

Similar Reads