Is assigning a,b = c,a the same as b,a = a,c?
<p>Is assigning </p>

<pre><code>a,b = c,a
</code></pre>

<p>the same as </p>

<pre><code>b,a = a,c
</code></pre>

<p>It seems to be the same for the simple case where <code>a</code>, <code>b</code>, and <code>c</code> are numbers.</p>

<p>Is there a case where this fails?</p>

<p>No, there is no case where this fails. The two statements are exactly equivalent, because <code>a</code> and <code>b</code> are <em>independent</em>.</p>

<p>That's because the right-hand side values are put on the stack <em>first</em> before assignment takes place (from left to right). Assigning to <code>a</code> before <code>b</code> makes no difference, because <code>a</code> and <code>b</code> are entirely different names, and assignment to either one first won't affect the other.</p>

<p>So the first statement:</p>

<pre><code>a,b = c,a
</code></pre>

<p>is executed as (psuedo-bytecode<sup>*</sup>)</p>

<pre><code>PUSH C ON STACK
PUSH A ON STACK
SWAP TOP TWO VALUES OF STACK
POP TOP OF STACK, STORE IN A
POP TOP OF STACK, STORE IN B
</code></pre>

<p>while the second</p>

<pre><code>b,a = a,c
</code></pre>

<p>is executed as</p>

<pre><code>PUSH A ON STACK
PUSH C ON STACK
SWAP TOP TWO VALUES OF STACK
POP TOP OF STACK, STORE IN B
POP TOP OF STACK, STORE IN A
</code></pre>

<p>It doesn't matter what type the values referenced by <code>a</code>, <code>b</code> or <code>c</code> are.</p>

<p>Things can get more confusing if you were to <a href="https://stackoverflow.com/questions/13657704/simple-assignment-operator-become-complicated-in-python">chain assignments</a> and / or <a href="https://stackoverflow.com/questions/32127908/python-assignment-operator-precedence-a-b-ab-5">mix in subscriptions</a>. In all those cases the names being assigned to are not independent, and people usually don't realise that all assignment takes place <em>after</em> the right-hand side expression has been executed and that assignment takes place from left to right after that.</p>

<hr>

<p><sup>*</sup> See <a href="https://stackoverflow.com/questions/21047524/how-does-swapping-of-members-in-the-python-tuples-a-b-b-a-work-internally">How does swapping of members in the python tuples (a,b)=(b,a) work internally?</a> for actual bytecode examples.</p>

python python-2.7