What Is Tuple Unpacking In Python

Destructuring operation unpacking data structures into named references

def sum_naturals(n):
total, k = 0, 1 #SEE ABOVE
while k <= n:
total, k = total + k, k + 1
return total
>>> pair = (1,2)
>>> pair
(1,2)
>>> x,y = pair
>>> x
1
>>> y
2
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
a = 'Hello'
b = 'World'
a,b = b,a
>>>a
'World'
>>>b
'Hello'

--

--

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