miik
miik

Reputation: 663

reversing the tuples in a list

I have this list:

[(3, 28), (25, 126), (25, 127), (26, 59)]

How can I turn it into this:

[(28, 3), (126, 25), (127, 25), (59, 26)]

I just want to reverse what is in the tuple

Upvotes: 1

Views: 121

Answers (5)

jamylak
jamylak

Reputation: 133574

Funny alternative

>>> L = [(3, 28), (25, 126), (25, 127), (26, 59)]
>>> zip(*zip(*L)[::-1])
[(28, 3), (126, 25), (127, 25), (59, 26)]

Or for some evil premature optimization:

>>> from operator import itemgetter
>>> L = [(3, 28), (25, 126), (25, 127), (26, 59)]
>>> map(itemgetter(slice(None, None, -1)), L)
[(28, 3), (126, 25), (127, 25), (59, 26)]

Timings:

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59)
]" "[i[::-1] for i in L]"
1000000 loops, best of 3: 1.21 usec per loop   

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59)
]" "zip(*zip(*L)[::-1])"
100000 loops, best of 3: 2.26 usec per loop   

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59)
]; from operator import itemgetter;" "map(itemgetter(slice(None, None, -1)), L)"    
100000 loops, best of 3: 1.69 usec per loop

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59)
]*100" "[i[::-1] for i in L]"
10000 loops, best of 3: 87.4 usec per loop

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59)
]*100" "zip(*zip(*L)[::-1])"
10000 loops, best of 3: 67.1 usec per loop

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59)
]*100;from operator import itemgetter;" "map(itemgetter(slice(None, None, -1)),
L)"
10000 loops, best of 3: 66.1 usec per loop

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59)
]*100000" "[i[::-1] for i in L]"
10 loops, best of 3: 108 msec per loop

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59)
]*100000" "zip(*zip(*L)[::-1])"
10 loops, best of 3: 109 msec per loop

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59)
]*100000;from operator import itemgetter;" "map(itemgetter(slice(None, None, -1)
), L)"
10 loops, best of 3: 82.9 msec per loop

Upvotes: 0

kaitian521
kaitian521

Reputation: 578

>>> L =  [(3, 28), (25, 126), (25, 127), (26, 59)]
>>> [(i[1], i[0]) for i in L]

may be useful just for two element.

Upvotes: 0

Rusty Rob
Rusty Rob

Reputation: 17173

If you know the tuples will only be of length 2:

[(b, a) for a, b in lst]

Upvotes: 7

John La Rooy
John La Rooy

Reputation: 304215

Use a slice with a step of -1

>>> [x[::-1] for x in [(3, 28), (25, 126), (25, 127), (26, 59)]]
[(28, 3), (126, 25), (127, 25), (59, 26)]

Upvotes: 0

Volatility
Volatility

Reputation: 32300

>>> lst = [(3, 28), (25, 126), (25, 127), (26, 59)]
>>> [i[::-1] for i in lst]
[(28, 3), (126, 25), (127, 25), (59, 26)]

[::-1] uses the slice syntax to reverse the container preceding it. Note this will only work with containers where the slice syntax is supported.

Upvotes: 7

Related Questions