Python Program to Unpack Tuple Items

Write a Python Program to Unpack Tuple Items. By assigning each tuple item to a variable, we can unpack the tuple items. Here, we assigned four tuple items to four different variables.

# Unpack Tuple Items

emp = ("John", 22, "Developer", 45000)
print(emp)

name, age, profession, sal = emp
print(name)
print(age)
print(profession)
print(sal)
Program to Unpack Tuple Items

If you don’t want any value, use the _ symbol to skip that value from being assigned to a variable. For example, we don’t want the second value, and without assigning it to some variable, you can’t assign the third value. In such scenarios, we can skip that second value by assigning it to the _ symbol.

fruits = ('apple', 'banana', 'mango')

a, _, c = fruits
print(a)
print(c)
apple
mango

Python Program to Unpack Tuple Items using *

By using the *, we can assign multiple unpacked tuple items to a single variable. For instance, name, *age, sal = emp unpack emp tuple and assign name as John, sal as 45000, and all the remaining tuple items to age. For more examples, refer to the Python Basic Programs.

# Unpack Tuple Items

emp = ("John", "Root", 22, "Developer", 45000)
print(emp)

name, *age, sal = emp
print(name)
print(age)
print(sal)

print("==========")
name, age, *sal = emp
print(name)
print(age)
print(sal)

print("==========")
*name, age, prof, sal = emp
print(name)
print(age)
print(prof)
print(sal)

The tuple unpack output is as shown below. Check out the Python Tuple.

('John', 'Root', 22, 'Developer', 45000)
John
['Root', 22, 'Developer']
45000
==========
John
Root
[22, 'Developer', 45000]
==========
['John', 'Root']
22
Developer
45000

The following program combines the _ symbol and asterisk (*) to ignore multiple tuple elements while unpacking. The program below ignores the employee’s second name, age, and profession.

emp = ("John", "Root", 22, "Developer", 45000)
name, *_, salary = emp
print(name)
print(salary)
John
45000

Program to unpack nested tuple items

Using the same technique, we can unpack nested tuple items. If we use a, b, c, d = n, then print(c) returns (10, 20). So, we are unpacking the nested tuples by assigning them to variables.

n = (1, 2, (10, 20), 5)
a, b, (c, d), e = n
print(a)
print(b)
print(c)
print(d)
print(e)
1
2
10
20
5

Also Read