Python: Unpack Tuple

In python, tuples are similar to list in some cases but tuples are immutable and list are mutable. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable.

When we create tuple we assign values to tuple know as packing, but in python we are allowed to extract values back to variables are known as unpacking.

Example:

tup = ("apple","mango","cherry","pineapple")
(s1,s2,s3,s4) = tup

print(s1)
print(s2)
print(s3)
print(s4)

Output:

apple
mango
cherry
pineapple
fruits = ("apple", "banana", "cherry", "strawberry")
(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)

Output:

apple
banana
['cherry', 'strawberry']
Tags