I know that a,b = b,a
is basically assigning a tuple (a,b)
the values of another tuple (b,a)
. This is, essentially, swapping the values form a
to b
and from b
to a
. Thus, causing a "swap".
This is the functionality of the swap()
function in C++.
From research, I have seen that C++'s swap()
function uses a third temporary variable to perform the swap. I haven't been able to find how is a,b = b,a
implemented in python.
How is a,b = b,a
implemented?
Does python also use a third temporary variable? If it doesn't, how does it work?
How do both operations compare in terms of speed? I'm guessing that if python also uses a third variable, the difference in execution time would be due to python being interpreted.
Edit: All answers are great, but the community seems to think that Sapan's is the best one. Also thanks to a_guest, whom, although didn't post an answer, gave us a great deal of information in the comments. Also: everyone seems to agree that swap()
is faster just because its C++. I don't necessarily agree with that. Python can be very fast if run as a frozen binary.