List Unpacking in Python
In Python, unpacking a list means extracting its elements and assigning them to variables (or passing them into functions) without manually indexing.
Basic Unpacking We can assign list elements directly to variables:
Python
# Example list numbers = [10, 20, 30] # Unpacking into variables a, b, c = numbers print(a) # 10 print(b) # 20 print(c) # 30
⚠️ If the number of variables doesn’t match the number of items, Python will raise a ValueError.
Using * (Star Operator) The * operator allows flexible unpacking, capturing multiple elements at once.
Python
numbers = [10, 20, 30, 40, 50] # First element into 'a', last into 'c', middle into 'b' a, *b, c = numbers print(a) # 10 print(b) # [20, 30, 40] print(c) # 50
This is useful when we don’t know the exact number of elements.
Unpacking in Loops
Python
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
for number, word in pairs:
print(number, word) Output: 1 one
2 two
3 three