Rotating a two-dimensional array in Python

paldepind picture paldepind · Dec 7, 2011 · Viewed 95.8k times · Source

In a program I'm writing the need to rotate a two-dimensional array came up. Searching for the optimal solution I found this impressive one-liner that does the job:

rotated = zip(*original[::-1])

I'm using it in my program now and it works as supposed. My problem though, is that I don't understand how it works.

I'd appreciate if someone could explain how the different functions involved achieves the desired result.

Answer

Andrew Clark picture Andrew Clark · Dec 7, 2011

Consider the following two-dimensional list:

original = [[1, 2],
            [3, 4]]

Lets break it down step by step:

>>> original[::-1]   # elements of original are reversed
[[3, 4], [1, 2]]

This list is passed into zip() using argument unpacking, so the zip call ends up being the equivalent of this:

zip([3, 4],
    [1, 2])
#    ^  ^----column 2
#    |-------column 1
# returns [(3, 1), (4, 2)], which is a original rotated clockwise

Hopefully the comments make it clear what zip does, it will group elements from each input iterable based on index, or in other words it groups the columns.