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.
Consider the following two-dimensional list:
Lets break it down step by step:
This list is passed into
zip()using argument unpacking, so thezipcall ends up being the equivalent of this:Hopefully the comments make it clear what
zipdoes, it will group elements from each input iterable based on index, or in other words it groups the columns.