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],Lets break it down step by step:
[3, 4]]
original[::-1] # elements of original are reversedThis list is passed into zip() using argument unpacking, so the zip call ends up being the equivalent of this:
[[3, 4], [1, 2]]
zip([3, 4],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.
[1, 2])
# ^ ^----column 2
# |-------column 1
# returns [(3, 1), (4, 2)], which is a original rotated clockwise