Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to know how the swapping of values of a and b works, kindly refer to the below code:

In [55]: a = 5

In [56]: b = 6

In [57]: (a, b) = (b, a)

In [58]: a

Out[58]: 6

In [59]: b

Out[59]: 5

1 Answer

0 votes
by (108k points)

Please to inform that Python is the right-hand side code from the left-hand side code. First, the right-hand side is executed, and the result is collected on the stack, and then the left-hand side names are specified using opcodes that extract the values from the stack again.

For the two or three elements, Python just uses the stack directly:

>>> import dis

>>> def foo(a, b):

...     a, b = b, a

... 

>>> dis.dis(foo)

  2           0 LOAD_FAST                1 (b)

              3 LOAD_FAST                0 (a)

              6 ROT_TWO             

              7 STORE_FAST               0 (a)

             10 STORE_FAST               1 (b)

             13 LOAD_CONST               0 (None)

             16 RETURN_VALUE        

For more information, you can refer to the Python tutorial.

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

Browse Categories

...