简体   繁体   中英

Is assigning a,b = c,a the same as b,a = a,c?

Is assigning

a,b = c,a

the same as

b,a = a,c

It seems to be the same for the simple case where a , b , and c are numbers.

Is there a case where this fails?

No, there is no case where this fails. The two statements are exactly equivalent, because a and b are independent .

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

So the first statement:

a,b = c,a

is executed as (psuedo-bytecode * )

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

while the second

b,a = a,c

is executed as

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

It doesn't matter what type the values referenced by a , b or c are.

Things can get more confusing if you were to chain assignments and / or mix in subscriptions . In all those cases the names being assigned to are not independent, and people usually don't realise that all assignment takes place after the right-hand side expression has been executed and that assignment takes place from left to right after that.


* See How does swapping of members in the python tuples (a,b)=(b,a) work internally? for actual bytecode examples.

It's the same in all cases, no matter what you're working with. So long as statements are equivalent (like yours are), the result will be the same.

简短答案-----“是” .. a,b = c,a表示a = c和b = a ... b,a = a,c表示b = a和a = c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM