Lists are a special type of container object in Python that can be used to hold values. The act of storing values into a List is known as packing. Similarly, we can perform an “unpack” operation, where we extract values from List into regular Python variables.
Did you know? The same operation works on tuples too!
Unpacking Lists in Python
In this example we will be unpacking a list of values into separate variables.
There is only one requirement, which is that the number of variables on the left-side of the equals to operator, should be equal to the number of elements in the list.
# Packing Values into a list
mylist = ["Purple", "Blue", "Black"]
# Unpacking from a list
x1, x2, x3 = mylist
print(x1)
print(x2)
print(x3)
Purple
Blue
Black
It goes without saying, that the type of the variables will be the same as the values inside the list.
Here is another interesting feature available in List unpacking.
Let’s say you have a list containing 10 values, and you only want the first two to be unpacked into individual variables. Or maybe you want the first and last values in the list, and the rest to be stored in a separate list. Well, for this we have the special asterisk operator!
The below code places the first two values from the list into x1 and x2, and the rest into x3. Try changing the position of the asterisk yourself and checking the output.
# Packing Values into a list
mylist = ["Purple", "Blue", "Black", "Red", "White"]
# Unpacking from a list
x1, x2, *x3 = mylist
print(x1)
print(x2)
print(x3)
Purple
Blue
['Black', 'Red', 'White']
Bear in mind that only one special unpack operation is allowed at a time. You cannot include more than * amongst the unpacked variables.
Unpack a List in Function Calls
You can also unpack lists directly within function calls. This way you don’t have to add an extra step for storing values in new variables before passing them into the function.
def add(x, y):
print( x + " " + y )
# Packing Values into a list
mylist = ["Hello", "World"]
# Unpacking from a list
add(*mylist)
Hello World
This marks the end of the How to unpack a List in Python Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.