Home > Enterprise >  Reverse column in a 2D list in Python
Reverse column in a 2D list in Python

Time:07-06

I have a 2D list called tab:

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

with tab[lines][columns]. For instance, tab[0][1] = 2. I want to reverse the order of each column to get the output format:

7 8 9
4 5 6
1 2 3

CodePudding user response:

You need to use [::-1] operator as if it were a string:

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

l = l[::-1]
print(l)

Output:

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

CodePudding user response:

You can also call reverse() to reverse the order in a list. In your case, this would mean doing the following:

>>> tab.reverse()
>>> tab
[[7, 8, 9], [4, 5, 6], [1, 2, 3]]

If you wanted to reverse the order on the minor index of your 2D array, you could combine this with map, like so:

>>> list(map(lambda c: c.reverse(), tab))
>>> tab
[[3, 2, 1], [6, 5, 4], [9, 8, 7]]
  • Related