Help me with the a, b = something

I’ve seen somebody using this kind of code… and would like to know what it is used for and what it gives
ex1) hour, minute = s.split(’:’)
ex2) t, o = divmod(int(minute), 10)
ex3) d,m = divmod(x,10)
thanks for any help

Syntax sugar for getting things out of iterables into variables or arguments, mostly referred to as unpacking, but also spreading or pattern matching. Some languages like haskell and erlang take these further than syntax sugar and also use them for flow control based on matching, and verifying matching values.

a, b = b, a  # b, a is a tuple, therefore iterable
c = 1, 3
print(c)  # (1, 3)
[[a], b, [[[c]]]] = [[1], 2, [[[3]]]]
for key, value in somedict.items():
a, b, *rest = range(100)
a, *rest, b = range(100)
[*range(3), 7, 8, *range(5)]  # [0, 1, 2, 7, 8, 0, 1, 2, 3, 4]
d = {'k': 'v'}
d2 = {*d, 'k': 'vv'}  # get default pairs from d
d3 = {'k': 'vv', **d}  # overwrite with pairs from d (last mentioned is kept)
print(*range(3))  # 0 1 2 (individual arguments)

…I might have missed a few versions

Python2 can also do this in function parameters, but it was removed in python3, more trouble than it was worth or something like that

Not sure if it’s described anywhere other than

1 Like