Today's featured video:



The Power of Unpacking In Python

An in-depth guide to understanding the power and usage of unpacking in python. …

Updated October 25, 2023

An in-depth guide to understanding the power and usage of unpacking in python.

Understanding Unpacking in Python

Unpacking is a process where an iterable such as list, tuple or dictionary is broken down into individual components. This is commonly seen when passing arguments to functions or assigning values from a container to multiple variables simultaneously.

Here’s how it can be done:

numbers = [1, 2, 3, 4, 5]
a, b, c, d, e = numbers
print(a)  # Outputs: 1
print(b)  # Outputs: 2

As you can see, it assigns the first element of the list to a, second to b and so on.

List Unpacking is also applicable for dictionaries:

person = {'name': 'John', 'age': 30}
name, age = person
print(name)   # Outputs: John
print(age)    # Outputs: 30

Here name gets the value of ‘name’ key and age gets the value of ‘age’ key. This is very handy when we have a dictionary with multiple keys which need to be unpacked into separate variables or passed as function arguments.

It’s also possible to unpack elements from an iterable using the * operator:

numbers = [1, 2, 3, 4, 5]
a, *rest = numbers
print(a)   # Outputs: 1
print(rest) # Outputs: [2, 3, 4, 5]

In this case *rest gets the remainder of the list after the first element has been assigned to a.

This can also be done with dictionaries:

person = {'name': 'John', 'age': 30}
first, *others = person.items()
print(first)   # Outputs: ('name', 'John')
print(others)  # Outputs: [('age', 30)]

Here *others will contain the rest of the items from the dictionary in form of tuples.