Python Unpack List
Unpacking lists in Python is a feature that allows us to extract values from a list into variables or other data structures. This technique is useful for various situations, including assignments, function arguments and iteration. In this article, we’ll explore what is list unpacking and how to use it
Basic List Unpacking
In its simplest form, list unpacking can be used to assign values from a list to individual variables. Here's how it works:
# List with three elements
li = [1, 2, 3]
# Unpacking list elements into variables
a, b, c = li
print(a)
print(b)
print(c)
Output
1 2 3
Explanation:
- Here, the list "li" contains three elements: [1, 2, 3].
- These elements are unpacked into the variables a, b and c respectively.
- This allows you to access each list element directly through its assigned variable.
Let's explore other methods of unpacking lists:
Unpacking with the Star (*) Operator
Python 3 introduced the * operator, which enables us to capture multiple values in one variable. This is especially useful when we don't know the exact number of elements in the list or when we only want to extract a few elements.
Using * for Collecting Remaining Items
We can use * operator to unpack the remaining elements of a list into a variable. Here's how it works:
# List with five elements
li = [1, 2, 3, 4, 5]
# Unpacking the first two elements and collecting the rest
a, b, *rest = li
print(a)
print(b)
print(rest)
Output
1 2 [3, 4, 5]
Explanation:
- The first two elements, 1 and 2 are unpacked into "a" and "b".
- The *rest syntax collects all remaining items ([3, 4, 5]) into the variable rest.
- This feature is very useful when you want to unpack part of the list while capturing the rest for later use.
Using * in the Middle
We can also use * operator in the middle of unpacking to collect values between two known items.
# List with six elements
li = [1, 2, 3, 4, 5, 6]
# Unpacking with `*` in the middle
a, *mid, c = li
print(a)
print(mid)
print(c)
Output
1 [2, 3, 4, 5] 6
Explanation:
- The variable "a" receives the first item (1).
- The *mid captures the middle elements ([2, 3, 4, 5]).
- Finally, "c" captures the last item (6).
- This approach gives you fine control over how you unpack lists.
Unpacking Nested Lists
We can also unpack lists that contain nested lists (lists within lists). The same unpacking rules apply but we may need to unpack multiple levels of nesting.
# Nested list
li = [1, [2, 3], 4]
# Unpacking nested list
a, (b, c), d = li
print(a)
print(b)
print(c)
print(d)
Output
1 2 3 4
Explanation:
- The list "li" contains a sublist [2, 3].
- The inner list is unpacked directly into the variables "b" and "c" using parentheses.