What Is Tuple Unpacking In Python
2 min readMay 9, 2022
- The aim of this tutorial🔍 is to cover the subject of Tuple Unpacking in Python, defined as
Destructuring operation unpacking data structures into named references
To decrypt the definition, look for types and examples below. If in doubt, reach out to Multiple assignment and tuple unpacking improve Python code readability — Trey Hunner
1. LITERAL
- aka multiple assignment
- this is not only with a simple binding of literal values in a function that calculates the running total of natural numbers from a → b
- `total, k = 0, 1` unpacks the ordered pair `(0,1)` into `total = 0` and `k = 1`
def sum_naturals(n):
total, k = 0, 1 #SEE ABOVE
while k <= n:
total, k = total + k, k + 1
return total
— From 1.6 Higher-Order Functions @ SICP in Python
- Or another example
>>> pair = (1,2)
>>> pair
(1,2)
>>> x,y = pair
>>> x
1
>>> y
2
2. FUNCTIONAL
- say that you have a function to get the min and max values of a tuple
def minmax(items):
return min(items), max(items)
min, max = minmax(items)
# ALL PASSED
def test_minmax_tupple():
input = 1, 2, 3, 4, 5
result = minmax(input)
assert result == (1, 5)
def test_minmax_min():
input = 1, 5, 7
resultMin = minmax(input)[0]
assert resultMin == 1
def test_minmax_max():
input = 1, 33, 99
resultMax = minmax(input)[1]
assert resultMax == 99
def test_minmax_min_unpacked():
input = 1, 5, 7
resultMin, resultMax = minmax(input)
assert resultMin == 1
def test_minmax_max_unpacked():
input = 1, 33, 99
resultMin, resultMax = minmax(input)
assert resultMax == 99
3. NESTED
4. SWAPPING
- assign bindings
a = 'Hello'
b = 'World'
- use the form
a,b = b,a
- this
- packs
a
, andb
into a tuple on the right side of the assignment - unpacks the new tuple on the left — it reuses the names
a
andb
- verify
>>>a
'World'
>>>b
'Hello'