How to Unpack a List in Python [6 Methods]

In this Python article, I will explain how to unpack a list in Python. I will show different use cases for unpacking a list in Python.

To unpack a list in Python, directly assign list elements to variables (e.g., a, b, c = [1, 2, 3]), use the asterisk operator for variable-length lists (e.g., first, rest = [1, 2, 3, 4]), iterate over lists with a for loop (for x in my_list:), and pass list elements as function arguments using the asterisk (e.g., my_function(my_list)). These techniques enable efficient and flexible handling of list elements in various scenarios.

Unpack a List in Python

Unpacking a list in Python is a versatile and efficient way to assign the elements of a list to variables. This feature of Python simplifies code and enhances readability.

Methods to Unpack a List in Python

List unpacking allows us to assign items from a list to distinct variables in a single statement. This feature is useful in various scenarios, such as:

  • Unpack the list to variables
  • Using asterisks(*) operator
  • Using underscore(_)
  • Unpack nested list
  • Using for loop
  • As Function argument

Let’s see them one by one using some illustrative examples:

Method 1: Python unpack list to variables

In the most basic form, we can unpack a list in Python by assigning its elements to individual variables.

coordinates = [40.6892, -74.0445]
latitude, longitude = coordinates
print(f"Latitude: {latitude}, Longitude: {longitude}")

Output: Here, the variables are assigned the values respectively in Python.

Latitude: 40.6892, Longitude: -74.0445
How to Unpack a List in Python

This way we can unpack a list in Python by assigning values to the variables.

READ:  Python List index() method [With Examples]

Method 2: Unpacking of list in Python using asterisks(*) operator

Sometimes, we might not know the length of the list or the list is longer than the number of variables we have. In such cases, Python allows extended unpacking using an asterisk * operator.

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
most_populated, *others = cities
print(f"Most populated: {most_populated}, Others: {others}")

Output: The first variable is assigned the first element, and the second variable becomes a list containing the rest of the elements.

Most populated: New York, Others: ['Los Angeles', 'Chicago', 'Houston', 'Phoenix']
Unpack a list in Python

The asterisk operator can unpack a list in Python.

Method 3: Unpacking in Python List using underscore(_)

If we only need certain elements of a list, we can unpack them selectively using an underscore _ as a placeholder for the ignored elements in Python.

apollo11_dates = ["July 16, 1969", "July 20, 1969", "July 24, 1969"]
launch, _, landing = apollo11_dates
print(f"Launch: {launch}, Moon Landing: {landing}")

Output: Here, the middle elements will be ignored.

Launch: July 16, 1969, Moon Landing: July 24, 1969
Python List Unpacking

The underscore can be used to ignore the elements that don’t need to be unpacked from the list in Python.

Method 4: Unpack nested list in Python

Python also supports nested unpacking, which is useful for dealing with lists of lists or similar data structures.

states_and_capitals = [["California", "Sacramento"], ["Texas", "Austin"]]
(california, sacramento), (texas, austin) = states_and_capitals
print(f"{california}: {sacramento}, {texas}: {austin}")

Output: This is again assigning variables to unpack a list in Python.

California: Sacramento, Texas: Austin
Unpack list of list Python

This way we can unpack a list of lists in Python.

Method 5: Python unpack list in for loop

Unpacking of the list in Python can be combined with loops to iterate through lists of tuples or lists and unpack them.

landmarks = [("Statue of Liberty", "New York"), ("Golden Gate Bridge", "San Francisco")]
for landmark, city in landmarks:
    print(f"The {landmark} is located in {city}.")

Output: Here, each element is accessed with the help of the for loop in Python.

The Statue of Liberty is located in New York.
The Golden Gate Bridge is located in San Francisco.
python unpack list of tuples

This way we can use the for loop to unpack a list in Python.

READ:  Naming Convention in Python [With Examples]

Method 6: Python unpack list function call

Unpacking is not just limited to variable assignments. We can unpack a list in Python, directly into function arguments.

def display_date(day, month, year):
    print(f"Independence Day: {month} {day}, {year}")

independence_day = [4, "July", 1776]

Output: Here, we simply pass the list with the asterisk operator as function arguments in Python.

Independence Day: July 4, 1776
Python unpack list

This way we can unpack list Python as function arguments.


Understanding and utilizing how to unpack a list in Python using different methods with scenarios like assigning to the variables, using asterisks operator, for loop or as function arguments, and using underscore or can unpack the nested list can lead us to cleaner, more readable, and more efficient code.

The choice of the methods will be dependent upon the requirement of the code.

You may also like to read: