How to Unpack a List in Python?

Python Tutorials

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

Employees who enroll in a comprehensive Python training program will also have the opportunity to pursue exciting career opportunities in data science, web development, and machine learning.

Leave a Reply

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