Python Simple Swap Function
Solution 1:
It's because it assigns new values to s1
and s2
inside the swap0
function. These assignments do not propagate outside the function. You'll see that it works if you just copy and paste the function body in the place of the function call.
You can work around this by modifying the objects referenced by the arguments, rather than the arguments themselves:
def swap0(s1, s2):
assert type(s1) == list and type(s2) == list
tmp = s1[:]
s1[:] = s2
s2[:] = tmp
However, the easier and better way to do a swap in Python is simply:
s1, s2 = s2, s1
This, too, will only swap those particular references to the lists, but not the list contents themselves.
Solution 2:
As it is, your final print
will print out the original values of s1
and s2
. This is because you're only swapping them within the scope of the function. Doing so will not affect their values outside the function (i.e. after their values after the function has been called)
If they are mutable types (list
, set
, dict
, etc), then you could modify them in-place inside swap
. However, that restricts swap
to work only on mutable types.
You are therefore better off returning the inputs in reversed order:
def swap(s1, s2):
return s2, s1
s1 = 'a'
s2 = 'b'
s1, s2 = swap(s1, s2)
print s1, s2 # prints 'b a'
Of course, you could do this all in one line as follows:
s1, s2 = s2, s1
Cheers!
Solution 3:
The other answers explain what's going wrong. Here's a version that does what you want:
def swap(s1, s2):
assert isinstance(s1, list) and isinstance(s2, list)
s1[:], s2[:] = s2[:], s1[:]
See also: isinstance vs. type
Solution 4:
Inside the function, you're rebinding local variables s1
and s2
with the values on the right hand side (which are also local since you're using slices to make copies). Even if you change the contents of those local variables, you won't change the contents of the lists in the calling scope because they no longer refer to the same lists.
Solution 5:
Here is a one-line function that accomplishes your goal:
swap = lambda x: (x[1], x[0])
Post a Comment for "Python Simple Swap Function"