Ask Your Question

# 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

## 1 Answer

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)]


Or, using words instead:

>>> 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

## Comments

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!

( 2012-02-08 15:02:19 +0200 )edit

@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.

( 2012-02-08 15:37:31 +0200 )edit

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

( 2012-02-08 22:45:22 +0200 )edit

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.)

( 2012-02-09 14:54:48 +0200 )edit

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 :)

( 2012-02-09 16:06:54 +0200 )edit

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

Asked: 2012-02-08 10:41:42 +0200

Seen: 521 times

Last updated: Feb 08 '12