-2

I have the list l, with (x,y) pairs:

print(l)
[(4.476784, 50.820377), (4.466914, 50.83413), (4.466898, 50.843526), (4.461776, 50.84864), (4.460908, 50.850731), (4.461256, 50.851948)...]

I would like to switch the positions of the elements; that is, from (x,y) to (y,x). How could I do this? Thanks in advance.

JavierSando
  • 339
  • 1
  • 8
  • 1
    Do you want it to modify the original list or create a new one? (In both cases, it's a `for`-loop, just slightly different) – bereal Jan 04 '21 at 16:30
  • 1
    What have you tried? Which part is troubling you? Reading the existing values, swapping them, or writing them back? – zvone Jan 04 '21 at 16:30
  • The most efficient way is to modify the list in-place: `l[:] = [(y, x) for x, y in l]` – Timur Shtatland Jan 04 '21 at 16:35
  • The most efficient way would be to not change anything and simply read them backwards... – Tomerikoo Jan 04 '21 at 16:36
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). "Write this code for me" is off-topic for Stack Overflow. You have to make an honest attempt at the solution, and then ask a *specific* question about your implementation. Stack Overflow is not intended to replace existing tutorials and documentation. – Prune Jan 04 '21 at 16:43

2 Answers2

1

You can achieve it using list comprehension as:

l = [(4.476784, 50.820377), (4.466914, 50.83413), (4.466898, 50.843526), (4.461776, 50.84864), (4.460908, 50.850731), (4.461256, 50.851948)]

new_list = [x[::-1]  for x in l]

OR,

new_list = [(y, x)  for x, y in l]

where new_list holds:

[(50.820377, 4.476784), (50.83413, 4.466914), (50.843526, 4.466898), (50.84864, 4.461776), (50.850731, 4.460908), (50.851948, 4.461256)]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • https://stackoverflow.com/a/51755571/6045800 – Tomerikoo Jan 04 '21 at 16:35
  • @Tomerikoo It would be better to flag the question as duplicate than to comment on an answer ;) – zvone Jan 04 '21 at 16:42
  • @zvone As you might notice the question is already closed as a duplicate of the question to which I linked an answer... Just trying to show that this answer exists already and there is no reason to repeat it... – Tomerikoo Jan 04 '21 at 16:44
1
[(y, x) for x, y in l]

Tuples are immutable, so you can't literally reverse the tuples.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22