What Is Tuple Unpacking In Python

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

>>> 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'
a,b = b,a
  1. unpacks the new tuple on the left — it reuses the names a and b
>>>a
'World'
>>>b
'Hello'

5. SOURCES

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com