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
This way we can unpack a list in Python by assigning values to the variables.
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']
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
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
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.
This way we can use the for loop to unpack a list in Python.
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]
display_date(*independence_day)
Output: Here, we simply pass the list with the asterisk operator as function arguments in Python.
Independence Day: July 4, 1776
This way we can unpack list Python as function arguments.
Conclusion
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:
- How to Concatenate multiple Lists in Python
- Append multiple items to list Python
- How to add a string to a list in Python
- How to Reverse a List in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.