Unpacking a list assigns its items to separate variables. It allows you to store list elements under separate named variables.

In Python, you can unpack a list in the following ways.

Use Variable Assignment to Unpack List

Assign the items of the list to separate variables by declaring them (comma separated) on the LHS of the = operator with a list on the RHS. The number of variables should be equal to the number of items in the list.

>>> l = ['apple', 'ball', 'cricket']
>>> a, b, c = l
>>> a
'apple'
>>> b
'ball'
>>> c
'cricket'

Use * to Unpack List

Use the * operator before the list object to unpack or spread its elements.

>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> list3 = [*list1, *list2]
>>> list3
[1, 2, 3, 4, 5, 6]

This way of unpacking a list is useful in passing list items as arguments to a function.

def add(a, b, c):
    return a+b+c
    
num = [4, 5, 2]
print(add(*num))
#output 11
Post author avatar

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply

Leave a Reply