A clever one-liner to rotate 2D Arrays in Python
Here’s a fun question: say you want to rotate an array 90 degrees clockwise, like so:
1 2 3
4 5 6
7 8 9becomes
7 4 1
8 5 2
9 6 3How would you do it?

In psuedo-code, this would look something like:
original = [
[1,2,3],
[4,5,6],
[7,8,9],
]rotated = [
[7,4,1],
[8,5,2],
[9,6,3],
]
assert_equal(rotated, rotate_90_clockwise(original))I initially learned of a nice method where you reverse the given matrix (row-wise), then switch the x and y-coordinates.
So something like this:

But then, my mind was blown from learning of a method like this:

Beautiful, right? Let’s take a look at how it works:
list(zip(*m[::-1]))Working from the inside out, we have the following operations:
m[::-1] This reverses the original 2D array, row-wise. If we’re given [[1,2,3],[4,5,6],[7,8,9]] , this gives us [[7,8,9],[4,5,6],[1,2,3]].
Then, the asterisk *m unpacks the array. This means we’re calling zip on [7,8,9],[4,5,6],[1,2,3] , not [[7,8,9],[4,5,6],[1,2,3]] (observe the extra opening and end bracket in the latter).
Then, zip will take one element from each of the arrays and use that new array as part of its output until there are no more elements. For example:
- First iteration: take 7, 4, and 1. Row is [7,4,1].
- Second iteration: take 8, 5, and 2. Row is [8,5,2].
- Third iteration: take 9, 6, and 3. Row is [9,6,3].
Then there aren’t any more elements to pull from!
Finally, we need a list because zip returns an iterator in Python3.
The output of this function is[[7,4,1],[8,5,2],[9,6,3]] , which is exactly the answer we want.
Hope you also thought this one-liner was cool!
For more articles like this, follow me on Medium. Not a member yet? Join the community. Want more software engineering interview guides and coding question tips? Check out all of my writing organized by topic in this article.
If you have any requests for what I should write, please let me know!






