Packing, Unpacking & Extended Unpacking of Tuple in Python

In Python, tuples are immutable and ordered data structures. Tuples usually contain a heterogeneous sequence of elements. Though tuples can contain homogeneous collection as well. Elements in tuples are generally accessed either by unpacking or by using index.

This article explains packing, unpacking and extended unpacking in tuples with examples.

Packing of Tuple

Process of creating collection by comma separating items within parentheses ( ) is known as packing of tuple.

Example: Packing of Tuple

For example, we generally create tuple by using parentheses ( ) like:


# Packing
person_detail = ("Alex Smith", 34, "United States", "Colorado")

Here, we packed person details containing name, age, country & state to a tuple named person_detail.

Note: we generally use parentheses pair ( ) while creating tuple but they are not required.

Unpacking of Tuple

Assigning individual items from a tuple to individual variables using assignment operator is known as unpacking of tuples.

Example: Unpacking of Tuple


# Packing
person_detail = ("Alex Smith", 34, "United States", "Colorado")

# unpacking 
name, age, country, state = person_detail

# printing results
print("Name: ", name)
print("Age: ", age)
print("Country: ", country)
print("State: ", state)

Output

Name:  Alex Smith
Age:  34
Country:  United States
State:  Colorado

Here person_detail is unpacked to individual variables name, age, country & state.

Sometimes assigning every items from tuple to individual variable is not required. In those cases we can ignore them by using underscore ( _ ). For example if we want to unpack name & country only then we can do:


# Packing
person_detail = ("Alex Smith", 34, "United States", "Colorado")

# unpacking 
name, _, country, _ = person_detail

# printing results
print("Name: ", name)
print("Country: ", country)

Output

Name:  Alex Smith
Country:  United States

Note: programmers generally use underscore by convention but you can use any valid identifier.

Extended Unpacking

Sometimes it is required to unpack some specific items by skipping some items from a tuple. In those cases, writing underscores ( _ ) for every skipped items is not so helpful. In such cases extended unpacking is very useful. It can be done by using *_. See example below:

Example: Extended Unpacking

If we want to unpack name & state from person_detail then we can use extended unpacking as:


# Packing
person_detail = ("Alex Smith", 34, "United States", "Colorado")

# unpacking 
name,*_, state = person_detail

# printing results
print("Name: ", name)
print("Sate: ", state)

Output

Name:  Alex Smith
Sate:  Colorado