Unpacking Techniques
Basic Unpacking
Python provides multiple ways to unpack return values from functions. The most straightforward method is direct assignment:
def get_coordinates():
return 10, 20, 30
x, y, z = get_coordinates()
print(x, y, z) ## Output: 10 20 30
Partial Unpacking
Ignoring Specific Values
You can use underscore (_
) to ignore certain return values:
def get_complex_data():
return "user", 25, "admin", 1000
name, _, role, _ = get_complex_data()
print(name, role) ## Output: user admin
Advanced Unpacking Techniques
Starred Expressions
def get_student_scores():
return "Alice", 85, 90, 88, 92, 87
name, *scores = get_student_scores()
print(name) ## Output: Alice
print(scores) ## Output: [90, 88, 92, 87]
Unpacking Strategies
graph TD
A[Unpacking Techniques] --> B[Direct Assignment]
A --> C[Partial Unpacking]
A --> D[Starred Expressions]
A --> E[Nested Unpacking]
Nested Unpacking
def get_nested_data():
return [1, (2, 3)], 4
(a, (b, c)), d = get_nested_data()
print(a, b, c, d) ## Output: 1 2 3 4
Unpacking Comparison
Technique |
Use Case |
Example |
Direct Assignment |
Full unpacking |
x, y, z = func() |
Partial Unpacking |
Selective extraction |
name, _, role = func() |
Starred Expressions |
Variable-length unpacking |
name, *scores = func() |
Error Handling
def risky_function():
return 1, 2, 3
try:
x, y = risky_function() ## Raises ValueError
except ValueError as e:
print("Unpacking error:", e)
Best Practices
- Use unpacking for clear, readable code
- Be cautious with complex unpacking
- Understand the structure of returned values
At LabEx, we recommend mastering these unpacking techniques to write more elegant Python code.