-5

Note; This is a self Q&A. Please see my answer below.

Given a list of tuples:

l = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

I'd like to find the quickest and simplest way to reverse each individual tuple in x, so that I get:

[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
cs95
  • 379,657
  • 97
  • 704
  • 746
  • https://stackoverflow.com/questions/3794486/why-i-cant-reverse-a-list-of-list-in-python – slhck Jul 25 '17 at 20:17

3 Answers3

17
l2 = [t[::-1] for t in l]

Use standard negative-step slicing t[::-1] to get the reverse of a tuple, and a list comprehension to get that for each tuple.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • it would need converting to `tuple` to get the result you're expecting, but that's minor. – Jean-François Fabre Jul 25 '17 at 20:41
  • @Jean-FrançoisFabre Look at the number of down votes on this question. I'm sitting at 450 rep today, I'm not going to gain anything from this. Seriously, asking questions is basically shooting yourself in the foot. – cs95 Jul 25 '17 at 20:44
  • you got rep for your own answer though. And I don't agree with you about shooting yourself in the foot (that may be true for meta...): https://stackoverflow.com/questions/42223125/should-i-avoid-converting-to-a-string-if-a-value-is-already-a-string – Jean-François Fabre Jul 25 '17 at 20:46
9

This is quite simple actually, and there are a few ways, the simplest being a list comprehension. To reverse 2-tuples, just unpack them and swap:

[(y, x) for x, y in l]
# [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]

To reverse n-tuples, you can slice in reverse using tuple slicing ([::-1]):

[x[::-1] for x in l]
# [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
cs95
  • 379,657
  • 97
  • 704
  • 746
  • 2
    Did you just write that answer to your your own question within a minute of posting question? – Philippe Oger Jul 25 '17 at 20:16
  • 4
    @PhilippeOger: There's an option to post the answer along with the question. (Also, self-answered questions are fine.) – user2357112 Jul 25 '17 at 20:16
  • can anyone tell me what is that In and out? – Vicrobot Jun 02 '18 at 17:44
  • @Vicrobot erm, what In and Out \*whistles innocently\* – cs95 Jun 02 '18 at 17:47
  • @coldspeed Was that simply input and output of interpreter; or any syntax of python? – Vicrobot Jun 03 '18 at 14:53
  • @coldspeed.......... Also you mentioned that you was at 450 rep; that time; and now even in less than a year; in the list of top growing person on this site;... What's the source of such growth???..**just for curiosity** – Vicrobot Jun 03 '18 at 14:58
1

The easiest way to do this...

l=[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
l=[tuple(reversed(t)) for t in l]
sam-pyt
  • 1,027
  • 15
  • 26