0

My_list= [[1,2,3],[4,5,6],[7,8,9]] ———-> [[1,2,3],[6,5,4],[7,8,9]]

I tried using this with out success :

for i my_list:
    if my_list.index(i) != 0:
        i = i[::-1]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91

2 Answers2

1

Since Python for loops create local variables, you have to index into the outer list indexes and use % 2 == 1 to detect sublists with odd indexes.

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

for index, sublist in enumerate(my_list):
    if index % 2 == 1:
        my_list[index] = sublist[::-1]

print(my_list)

Outputs

[[1, 2, 3], [6, 5, 4], [7, 8, 9], [12, 11, 10]]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

Another option (in addition to @DeepSpace answer) is using Python's slicing notation (link) and assigning to slice (link):

In this example, we create slice starting from index 1 and step 2 and assign reverse sublist to it:

my_list = [[1,2,3],[4,5,6],[7,8,9]]

my_list[1::2] = (v[::-1] for v in my_list[1::2])

print(my_list)

Prints:

[[1, 2, 3], [6, 5, 4], [7, 8, 9]]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91