Unpacking Patterns
Advanced Unpacking Techniques
Multiple Variable Assignment
## Complex unpacking scenarios
first, *middle, last = [1, 2, 3, 4, 5]
print(first) ## Output: 1
print(middle) ## Output: [2, 3, 4]
print(last) ## Output: 5
Nested Unpacking
## Handling nested structures
(a, *b), *rest = [(1, 2), (3, 4), (5, 6)]
print(a) ## Output: (1, 2)
print(b) ## Output: []
print(rest) ## Output: [(3, 4), (5, 6)]
Unpacking Patterns Flow
graph TD
A[Original Iterable] --> B{Unpacking Strategy}
B --> C[First Elements]
B --> D[Middle Elements]
B --> E[Last Elements]
Pattern Matching Techniques
Pattern |
Description |
Example |
Head Extraction |
Capture first element |
x, *_ = [1, 2, 3] |
Tail Extraction |
Capture last element |
*_, y = [1, 2, 3] |
Selective Unpacking |
Ignore specific elements |
a, *_, b = [1, 2, 3, 4, 5] |
Function Argument Unpacking
def process_data(first, *args, last=None):
print(f"First: {first}")
print(f"Remaining: {args}")
print(f"Last: {last}")
process_data(10, 20, 30, 40, last=50)
## Output:
## First: 10
## Remaining: (20, 30, 40)
## Last: 50
Extended Unpacking in Comprehensions
## Dynamic list generation
numbers = [1, 2, 3, 4, 5]
expanded = [*numbers, 6, 7]
print(expanded) ## Output: [1, 2, 3, 4, 5, 6, 7]
Best Practices
- Use asterisk unpacking for readability
- Avoid overly complex unpacking
- Be mindful of performance with large iterables
LabEx recommends mastering these patterns to write more pythonic and efficient code.