Unpacking of list in python

Unpacking is a powerful feature in python. Using python list unpacking you can assign right-hand side values to the left-hand side. Using unpacking you can assign values in the list 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 list 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, list is created and then that list is passed as argument to the function. But as list contains multiple values, function unpacks that list and assign values in list to parameters.

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


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

Output:

Checkout the Recommended Posts:

Unpacking of tuples in python

List in python

Tuples in python

Dictionary in python

2D lists in python

Leave a Reply

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