Comma separated variable assignment [duplicate]

What you describe is tuple assignment:

a, b = 0, 1

is equivalent to a = 0 and b = 1.

It can however have interesting effects if you for instance want to swap values. Like:

a,b = b,a

will first construct a tuple (b,a) and then untuple it and assign it to a and b. This is thus not equivalent to:

#not equal to
a = b
b = a

but to (using a temporary):

t = a
a = b
b = t

In general if you have a comma-separated list of variables left of the assignment operator and an expression that generates a tuple, the tuple is unpacked and stored in the values. So:

t = (1,'a',None)
a,b,c = t

will assign 1 to a, 'a' to b and None to c. Note that this is not syntactical sugar: the compiler does not look whether the number of variables on the left is the same as the length of the tuple on the right, so you can return tuples from functions, etc. and unpack them in separate variables.

Leave a Comment