Unpacking of tuples in python

Unpacking is a powerful feature in python. Using python tuple unpacking you can assign right-hand side values to the left-hand side. Using unpacking you can assign values in tuples to variables at once.

Note:

When using unpacking number of variables on left hand side must be equal to number of values on right hand side.

Example:

names = ('John', 'Jane', 'Jim')
user1, user2, user3 = names
print(user1)
print(user2)
print(user3)

Output:

John
Jane
Jim

You can also pass optional arguments for python tuple unpacking. You can assign multiple values in one place or to one variable and also assign other values to other variables.

Example:

names = ('John', 'Jane', 'Jim', 'Jack', 'Tom')
user1, user2, *otherUsers = names
print(user1)
print(user2)
print(otherUsers)

Output:

John
Jane
[‘Jim’, ‘Jack’, ‘Tom’]

If you pass multiple optional arguments to function then function unpacks them.

Example:

In below example, tuple is created and then that tuple is passed as argument to the function. But as tuple contains multiple values, function unpacks that tuple and assign values in tuple to parameters.

def addition(a, b):
    return a + b


c = (40, 60)
print(addition(*c))

Output:

100

Checkout the Recommended Posts:

Unpacking of lists in python

Tuples in python

Lists in python

2D lists in python

Dictionary in python

Leave a Reply

Your email address will not be published. Required fields are marked *