-1

So I got this list:

my_old_list = [(1,2),(3,4),(5,6),(7,8),(9,0)]

and I would like to reverse the content of the elements to:

my_new_list = [(2,1),(4,3),(6,5),(8,7),(0,9)]

I have find a lot of different things, but it never really changes the list into the way I want.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
ejohalj
  • 37
  • 8
  • Since tuples are immutable, there is no way to reverse a tuple in-place. Creating a copy requires more space to hold all of the existing elements. Therefore, this exhausts memory. – zamir Jan 14 '20 at 20:30
  • `[(b, a) for (a, b) in my_old_list]` – Peter Wood Jan 14 '20 at 20:36

4 Answers4

2

Here's one way:

[tuple(reversed(i)) for i in my_old_list]
# [(2, 1), (4, 3), (6, 5), (8, 7), (0, 9)]

Or similarly:

[(*reversed(i),) for i in my_old_list]
# [(2, 1), (4, 3), (6, 5), (8, 7), (0, 9)]
yatu
  • 86,083
  • 12
  • 84
  • 139
1

try it :

my_old_list = [(1,2),(3,4),(5,6),(7,8),(9,0)]

for i in range(len(my_old_list)) :
    my_old_list[i] = my_old_list[i][::-1]

print(my_old_list)
AmirHmZ
  • 516
  • 3
  • 22
0
my_new_list = map(lambda tup: (tup[1], tup[0]), my_old_list)
Personman
  • 2,324
  • 1
  • 16
  • 27
0

I would use list comprehension here as follows:

new_list = res = [(sub[1], sub[0]) for sub in my_old_list ] 

Output

[(2, 1), (4, 3), (6, 5), (8, 7), (0, 9)]
Edeki Okoh
  • 1,786
  • 15
  • 27