-1

I have a list of lists of tuples in the following form:

a = [[( 0,  1),
      ( 2,  3),
      ( 4,  5)],

     [( 6,  7),
      ( 8,  9),
      (10, 11)],

     [(12, 13),
      (14, 15),
      (16, 17)]]

What I want to do, is to swap the two arguments inside the tuples.

I have tried the two following options, but without succes, the argumets keep their positions:

for i in range(0, len(a)-1):
    for j in range(0, len(a)/2):

        a[i][j] = a[i][j][1], a[i][j][0]

        a[i][j] = tuple(reversed(a[i][j]))

Every help would be very much appreciated

2 Answers2

0

Tuples are immutable, so you should replace the tuples with the reversed tuples, not try to modify the first tuple in-place:

for lst in a:
   for i, x in enumerate(lst):
      lst[i] = x[::-1]  

This takes updates the items at the position of each tuple in the list with a new reversed tuple (with reversed slice notation [::-1]) using list subscription.

To create a new list of lists with the swapped objects, you can use a list comprehension:

new_a = [[tup[::-1] for tup in lst]for lst in a]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

Consider changing your loops to:

for i in range(0, len(a)):
    for j in range(0, len(a[i])):
        a[i][j] = tuple(reversed(a[i][j]))

In order to iterate over a list of lists (of tuples, in this case), you need to make sure you're specifying the lengths of each part correctly. In len(a)-1 in the outer loop, you don't need the -1, as range(x,y) takes you from x to y-1 already. In the inner loop, you need to specify the length of the inner list.

@Moses has a good answer on why creating a new tuple is the correct approach.

N. P.
  • 170
  • 1
  • 3
  • 11