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

    rotated_map = []
    for i in range(len(m[0])):
      rotated_map.append([x[i] for x in m]) 
      print(rotated_map)

    """
    my result = [[5, 2, 6, 1], [9, 4, 3, 7], [1, 5, 3, 6], [8, 7, 2, 3]]

    desired result = [[8,7,2,3],
                      [1,5,3,6],
                      [9,4,3,7],
                      [5,2,6,1]]
    """

I am trying to rotate the list by putting all the last elements first from the lists into one list then the second to last element into another and so on until i get to the first element.

5 Answers5

2

Transpose the list with zip, then reverse it with the [::-1] syntax.

>>> m = [[5, 9, 1, 8], [2, 4, 5, 7], [6, 3, 3, 2], [1, 7, 6, 3]]
>>> list(map(list, zip(*m)))[::-1]
>>> [[8, 7, 2, 3], [1, 5, 3, 6], [9, 4, 3, 7], [5, 2, 6, 1]]

edit:

If you want pretty printing, it's probably easiest to use numpy arrays all the way.

>>> import numpy as np
>>> 
>>> m = [[5, 9, 1, 8], [2, 4, 5, 7], [6, 3, 3, 2], [1, 7, 6, 3]]
>>> m = np.array(m)
>>> m
>>> 
array([[5, 9, 1, 8],
       [2, 4, 5, 7],
       [6, 3, 3, 2],
       [1, 7, 6, 3]])
>>> 
>>> m.T[::-1]
>>> 
array([[8, 7, 2, 3],
       [1, 5, 3, 6],
       [9, 4, 3, 7],
       [5, 2, 6, 1]])

Note that m and m.T[::-1] share the same data, because m.T[::-1] is just another view of m. If you need to duplicate the data, use

result = m.T[::-1].copy()
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

You could use zip, unpacking your list of lists with the *, and inversing the result with [::-1]:

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

res = [list(i) for i in zip(*m)][::-1]

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

If numpy is an option, transposing is easier:

import numpy as np
>>> np.transpose(m)[::-1]
array([[8, 7, 2, 3],
       [1, 5, 3, 6],
       [9, 4, 3, 7],
       [5, 2, 6, 1]])
# or:
>>> np.flip(np.transpose(m),0)
array([[8, 7, 2, 3],
       [1, 5, 3, 6],
       [9, 4, 3, 7],
       [5, 2, 6, 1]])
sacuL
  • 49,704
  • 8
  • 81
  • 106
0

You can use numpy module to do it. It has the property to transpose the array. Check the below code:

import numpy as np
m = [[5,9,1,8],
    [2,4,5,7],
    [6,3,3,2],
    [1,7,6,3]]
arr = np.array(m).transpose()
new_list = []
for i in range(arr.shape[0]-1,-1,-1):
    new_list.append(list(arr[i]))

print(new_list)

Output:

[[8, 7, 2, 3], [1, 5, 3, 6], [9, 4, 3, 7], [5, 2, 6, 1]]
Sanchit Kumar
  • 1,545
  • 1
  • 11
  • 19
0

If you want to rotate the list clockwise:

list(map(list, zip(*m[::-1])))

Else, for anti-clockwise:

list(map(list, zip(*m)))[::-1]
0

use the reverse keyword

result = [[5, 2, 6, 1], [9, 4, 3, 7], [1, 5, 3, 6], [8, 7, 2, 3]]
result.reverse()
print(result)  

output:

[[8, 7, 2, 3], [1, 5, 3, 6], [9, 4, 3, 7], [5, 2, 6, 1]]
Golden Lion
  • 3,840
  • 2
  • 26
  • 35