r/pythontips • u/PurposeDevoid • 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 = 0or using tuple unpacking
a,b = 0,0you can actually do
a = b = 0Note 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 tempNote 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
> TrueStill, 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
6
u/TeamSpen210 Sep 11 '16
Additionally, this works with attributes or item access too, as well as with iterable unpacking: