Unpacking Tuples

Unpacking refers to assigning the elements of a tuple to individual variables. The number of variables must match the number of elements in the tuple unless you use the asterisk * operator.

Basic Unpacking

Example 1: Unpacking a Tuple into Variables

# Unpacking a tuple
tuple_data = ("Karthick AG", "Durai", "Vijay")
name1, name2, name3 = tuple_data
print(name1)
print(name2)
print(name3)

Output

Karthick AG

Durai

Vijay

Extended Unpacking with Asterisk

Example 2: Unpacking with Asterisk Operator

# Unpacking with asterisk
tuple_data = ("John", "Praveen", "Williams", "Karthick AG", "Durai", "Vijay")
first, *middle, last = tuple_data
print("First:", first)
print("Middle:", middle)
print("Last:", last)

Output

First: John

Middle: ['Praveen', 'Williams', 'Karthick AG', 'Durai']

Last: Vijay

Ignoring Values During Unpacking

Example 3: Using Underscore to Ignore Values

# Ignoring values during unpacking
tuple_data = (1, 2, 3, 4, 5)
first, *_, last = tuple_data
print("First:", first)
print("Last:", last)

Output

First: 1

Last: 5

Explanation: The underscore _ is commonly used as a placeholder for values that you want to ignore during unpacking.