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
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
>>> 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.
If you know the tuples will only be of length 2:
[(b, a) for a, b in lst]
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)]
>>> L = [(3, 28), (25, 126), (25, 127), (26, 59)]
>>> [(i[1], i[0]) for i in L]
may be useful just for two element.
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