Is there a standardized method to swap two variables in Python?
Python evaluates expressions from left to right. Notice that while
evaluating an assignment, the right-hand side is evaluated before the
left-hand side.Python docs: Evaluation order
That means the following for the expression a,b = b,a
:
- The right-hand side
b,a
is evaluated, that is to say, a tuple of two elements is created in the memory. The two elements are the objects designated by the identifiersb
anda
, that were existing before the instruction is encountered during the execution of the program. - Just after the creation of this tuple, no assignment of this tuple object has still been made, but it doesn't matter, Python internally knows where it is.
- Then, the left-hand side is evaluated, that is to say, the tuple is assigned to the left-hand side.
- As the left-hand side is composed of two identifiers, the tuple is unpacked in order that the first identifier
a
be assigned to the first element of the tuple (which is the object that was formerly b before the swap because it had nameb
)
and the second identifierb
is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers wasa
)
This mechanism has effectively swapped the objects assigned to the identifiers a
and b
So, to answer your question: YES, it's the standard way to swap two identifiers on two objects.
By the way, the objects are not variables, they are objects.
How swapping variables is implemented in Python?
It's a simple bytecode operation which doesn't need any intermediate variables to do the swap. See this demo:
import dis
code = '''
a = input()
b = input()
a, b = b, a
'''
dis.dis(code)
Output:
2 0 LOAD_NAME 0 (input)
2 CALL_FUNCTION 0
4 STORE_NAME 1 (a)
3 6 LOAD_NAME 0 (input)
8 CALL_FUNCTION 0
10 STORE_NAME 2 (b)
4 12 LOAD_NAME 2 (b)
14 LOAD_NAME 1 (a)
16 ROT_TWO
18 STORE_NAME 1 (a)
20 STORE_NAME 2 (b)
22 LOAD_CONST 0 (None)
24 RETURN_VALUE
Note: Like bytecode as a whole, this is of course just an implementation detail of CPython.
How do you swap two local variables within a function in python
I think this is what you want to achieve:
def twobytwo(m):
last = len(m)-1
for i in range(0, last):
m[i][i], m[i][last] = m[i][last], m[i][i]
m[i][i], m[last][last] = m[last][last], m[i][i]
m[i][i], m[last][i] = m[last][i], m[i][i]
return m
print(twobytwo([[0, 1], [2, 3]]))
EDIT:
If you still want to maintain the function swap
:
def swap(i, j):
return j, i
a, b = swap(a, b)
But I think a, b = b, a
is good enough.
Python: how to change values of two dictionaries
Try this
worker_1, worker_2 = worker_2, worker_1
Related Topics
How to Fix "Attempted Relative Import in Non-Package" Even With _Init_.Py
Split String With Multiple Delimiters in Python
Using @Property Versus Getters and Setters
Annotate Bars With Values on Pandas Bar Plots
Difference Between Map, Applymap and Apply Methods in Pandas
Is There Any Pythonic Way to Combine Two Dicts (Adding Values For Keys That Appear in Both)
Store Output of Subprocess.Popen Call in a String
How to Create a Daemon in Python
Understanding Repr( ) Function in Python
How to Split the Definition of a Long String Over Multiple Lines
How to Capture Sigint in Python
Saving Utf-8 Texts With Json.Dumps as Utf8, Not as \U Escape Sequence
Converting Between Datetime, Timestamp and Datetime64