Reputation: 74
Is there any difference between:
a=b=c
and
b = c
a = c
in python?
Will the interpreter read those things differently?
And what is the side effect when i use first/second method, if it has side effects?
Upvotes: 0
Views: 59
Reputation: 798686
If c
is an existing object then both pieces of code will have the same effect, binding both a
and b
to the same existing object.
If c
is a literal then the first will bind them to the same object whereas the second will create two separate objects (for a certain value of "create"; the difference only matters for mutable objects) and bind them to each name.
Upvotes: 1
Reputation: 2884
For your future googling, this is known as a "chained assignment" or "nested assignment". As shown by this answer chained assignments are useful for forcing the interpreter to only evaluate the right hand expression once. For example:
a = b = myComputeHeavyFunc() # Only one evaluation
will only evaluate myComputeHeavyFunc()
once where as the multi-line solution evaluates the function twice, providing a performance loss:
a = myComputeHeavyFunc() # One evaluation
b = myComputeHeavyFunc() # Another evaluation
Upvotes: 2