tags:

views:

331

answers:

5
+6  Q: 

Pythonic Swap?

I found that i have to perform a swap in python and i write something like this.

arr[first], arr[second] = arr[second], arr[first]

I suppose this is not so pythonic. Does somebody know how to do a swap in python more elegent?

EDIT: I think another example will show my doubts

self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]

is this the only available solution for swap in python? I did searched a lot but didn't find a nice answer...

+11  A: 

It is pythonic indeed.

Adam Matan
Adam Matan
+1  A: 

It's difficult to imagine how it could be made more elegant: using a hypothetical built-in function ... swap_sequence_elements(arr, first, second) elegant? maybe, but this is in YAGGI territory -- you aren't going to get it ;-) -- and the function call overhead would/should put you off implementing it yourself.

What you have is much more elegant than the alternative in-line way:

temp = arr[first]
arr[first] = arr[second]
arr[second] = temp

and (bonus!) is faster too (on the not unreasonable assumption that a bytecode ROT_TWO is faster than a LOAD_FAST plus a STORE_FAST).

John Machin
+1  A: 

a, b = b, a is about as short as you'll get, it's only three characters (aside from the variable names).. It's about as Python'y as you'll get

One alternative is the usual use-a-temp-variable:

self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]

..becomes..

temp = self.memberlist[someindexB]
self.memberlist[someindexB] = self.memberlist[someindexA]
self.memberlist[someindexA] = temp

..which I think is messier and less "obvious"

Another way, which is maybe a bit more readable with long variable names:

a, b = self.memberlist[someindexA], self.memberlist[someindexB]
self.memberlist[someindexA], self.memberlist[someindexB] = b, a
dbr
+7  A: 
Alex Martelli
A: 

I suppose you could take advantage of the step argument of slice notation to do something like this:

myarr[:2] = myarr[:2][::-1]

I'm not sure this is clearer or more pythonic though...

arcanum