1

I have a list of tuples:

ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]

I want to reverse the order of each tuple in the list.

ls = [('there', 'hello'), ('up', 'whats'), ('idea', 'no')]

I know tuples are immutable so I'll need to create new tuples. I'm not really sure what's the best way to go about it. I could change the list of tuples into a list of lists, but I'm thinking there might be a more efficient way to go about this.

  • in python2, `map(reversed, ls)` would have sufficed, in python3 you'd have to write `list(map(tuple, map(reversed, ls)))` for the same result. list comprehension is a better way to go – njzk2 May 21 '20 at 10:19

2 Answers2

6

Just use a list comprehension along the following lines:

ls = [tpl[::-1] for tpl in ls]

This uses the typical [::-1] slice pattern to reverse the tuples.

Also note that the list itself is not immutable, so if you needed to mutate the original list, and not just rebind the ls variable, you could use slice assignment:

ls[:] = [tpl[::-1] for tpl in ls]

This is the short-hand equivalent of a loop-based approach à la:

for i, tpl in enumerate(ls):
    ls[i] = tpl[::-1]
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Input:

ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]

ls = [(f,s) for s,f in ls]
print(ls)

Output:

[('there', 'hello'), ('up', 'whats'), ('idea', 'no')]

Red
  • 26,798
  • 7
  • 36
  • 58