Tuple Unpacking¶
Zero-dependency Python snippets for unpacking tuples using the standard library.
6 snippets available in this sub-category.
Simple¶
Basic tuple unpacking¶
tuple
unpacking
assignment
data-structures
Assign tuple elements to variables
Notes
- Number of variables must match tuple length
Unpacking in for loops¶
tuple
unpacking
loop
iteration
data-structures
Unpack tuple elements directly in loops
Notes
- Works with any iterable of tuples
Complex¶
Extended unpacking (Python 3+)¶
tuple
extended-unpacking
star
ignore
data-structures
Use * to capture multiple elements, ignore with _
tup = (1, 2, 3, 4, 5)
first, *middle, last = tup
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
# Ignore values with _
x, _, z = (10, 99, 30)
print(x, z) # 10 30
Notes
-
- can be used in any position except the first or last
- _ is a common convention for unused values
Swapping variables with tuple unpacking¶
tuple
swap
unpacking
data-structures
Swap variables without a temporary variable
Notes
- Pythonic way to swap values
Nested tuple unpacking¶
tuple
nested
unpacking
data-structures
Unpack nested tuples in a single statement
Notes
- Structure of variables must match tuple nesting
Unpacking with * in function arguments¶
tuple
unpacking
function
arguments
data-structures
Use * to unpack tuple into function arguments
Notes
- *args unpacks tuple elements as positional arguments
🔗 Cross Reference¶
- Reference: See 📂 Create and Use Tuples
- Reference: See 📂 Named Tuple Usage
🏷️ Tags¶
tuple
, unpacking
, extended-unpacking
, swap
, nested
, function-args
, data-structures
📝 Notes¶
- Tuple unpacking is a powerful and Pythonic feature
- Use * for flexible unpacking and function calls