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:
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: