~ read.

Rotating a two-dimensional array in Python

I was solving one of the learning tasks on Python and had to rotate two dimensional array clockwise. In Java i would have to loop over array and pass values into newly created array, but in Python i could solve this with one line of code :
 template = zip(*template[::-1])
And an explanation for this line is next : 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.
comments powered by Disqus
comments powered by Disqus