r/pythontips • • Sep 11 '16

Syntax Python chained assignment (a=b=0)

When assigning variables to the same number for some kind of initialization, rather than doing

a = 0
b = 0

or using tuple unpacking

a,b = 0,0

you can actually do

a = b = 0

Note that this can be used with any object on the RHS, and that:

a = b = an_obj()

is equivalent to

temp = an_obj()
a = temp
b = temp
del temp

Note that the chain length for assignment can be longer than just two variables, so a = b = c = d = 0 is valid (though it probably gets a bit ugly if you go too far). Specifically, what happens is that the far RHS is evaluated and then from left to right assignments of the variables are made to it. This is different to C.

Obviously, you should be careful if you use this when assigning to mutable objects (such as lists), because of the typical object reference trip-ups in python that can be seen here; it means that

a = b = []
a.append(5)
print(b)
> [5]

a is b
> True

Still, I think it looks a bit neater in some cases, is very nice for number assignment and is a cool little tip :)

The specific python documentation is here, and you can read more about them on stack overflow here and here

26 Upvotes

3 comments sorted by

6

u/TeamSpen210 Sep 11 '16

Additionally, this works with attributes or item access too, as well as with iterable unpacking:

(a, b, c) = obj.value = array[3] = value

1

u/tomkatt Sep 12 '16

Be careful with iterable assignment though.

If you assign the values of a list like a, b, c = list[] and list is longer or shorter than three values, you'll get an error.

2

u/TeamSpen210 Sep 12 '16

That's actually an advantage - it serves as an assertion that the list is exactly the expected size. If you do want to allow variable lengths, you can do a, b, c, *extra = to collect extra values in a list.