# Swap coordinates of list elements

Suppose I have list like

L = [(2,3), (4,5), (6,7)]


What's the easiest way to transform it to this list:

L'=[(3,2),(5,4),(7,5)]


i.e. swap the coordinates in each entry.

edit retag close merge delete

Sort by » oldest newest most voted There are several ways to do this. Which one I'd use would depend more upon the context, because I'd probably write the one which generalized most naturally.

First, explicitly (useful if we're sticking with 2D or if I might be interested in other transformations):

>>> L = [(2,3), (4,5), (6,7)]
>>> M = [(y,x) for x,y in L]
>>> M
[(3, 2), (5, 4), (7, 6)]


or maybe using slice notation (seq[start:stop:step]):

>>> M = [v[::-1] for v in L]
>>> M
[(3, 2), (5, 4), (7, 6)]


>>> M = [tuple(reversed(v)) for v in L]
>>> M
[(3, 2), (5, 4), (7, 6)]
>>> M = list(tuple(reversed(v)) for v in L)
>>> M
[(3, 2), (5, 4), (7, 6)]


And if the objects are really vectors, then maybe I'd use a rotation matrix. All depends, but I have to admit if there were only two things to swap I'd reach for the first method.

more

Umm, wouldn't you try to use the *fastest* one, all else being equal? Using L = [(randint(0,10),randint(0,10)) for i in range(10000)], the first one wins hands down. A little (numerical, not # of ops) analysis shows that the first two options are slightly superlinear in the length of the list while the last is nearly exactly O(n^2). Anyway, go with the first one if you really only have pairs!

@kcrisman: well, sometimes I might want to use the most general one, all else being equal. Not everything's sliceable. (slicable?) I don't see O(n^2), though-- which list length are you talking about, L or v? Maybe I typed it wrong.

Sorry, I was referring to L. Adding a zero multiplied the timing by about 100 each time, it was quite impressive.

I really don't seem to be able to reproduce this. timeit shows almost exactly linear growth for me. Could you double-check that? (Could be a memory reallocation thing? Hard to see where the nonlinearity would come from otherwise.)

Strange - I could have sworn - but I get linear now too. Huh. That doesn't change the point that the first option still is the fastest :)