About swap, in C++, we can swap two by std::swap(x, y);.
x and y are passed into swap as reference.
But in Python, can we also write a swap function which can do the swap the same way as in C++?
The Python version of swap I implemented is kinda stupid:
def swap_in_python(x, y):
return y, x
#so when swapping a and b, I usually do it like this
a, b = swap_in_python(a, b)
This is really cumbersome, but we can’t pass reference or pointer as what we can do in C++, right?
EDIT:
Is there any other way not employing assignment(not using =)?
Actually, in Python, it’s much more elegant:
You don’t have to call a function at all. And, yes, as per the comments, the parentheses are unnecessary here. I still prefer them since I believe they make the intent clearer.
Following edit:
Possibly, though I don’t know of one, and I can’t imagine it would be simpler or more readable than the basic way shown above. If you’re looking for a more complicated way of doing things that can be done simply, might I suggest that you’re in the wrong mindset? 🙂