1

In python, what is the difference between

x = y = 0

and

x = 0
y = 0
Xceptions
  • 209
  • 2
  • 11
  • 1
    One of them is a single line, the other is two lines. That's the difference. In other cases (e.g. when assigning mutable objects like lists) there would be a difference. – kaya3 Apr 15 '21 at 06:07
  • Even for immutable objects it won't be the same thing (i.e. `x is y` may return `False` for the latter). Technically speaking the exact equivalent would be `y = 0` then `x = y`. – Selcuk Apr 15 '21 at 06:12

1 Answers1

6

IIRC, there's no difference for immutable types (like int in the example). But beware of potential issues when doing chained assignment for mutables:

>>> foo = bar = []
>>> print(id(foo) == id(bar))

Out: True

>>> foo.append(1)
>>> bar

Out: [1]

So here you inadvertently modify both lists since they both refer to the same set of memory addresses.

EDIT: Actually, there is a difference in your example. The one-liner chained assignment is more compact but might become less legible so I personally almost never use those.

NotAName
  • 3,821
  • 2
  • 29
  • 44