Python Matrix Transpose oneliner two ways

I was asked to write some python code to transpose a matrix (represented as a list of lists) during a recent interview. I quickly came up with a oneliner using list comprehension like this:

It works, but I was asked to make it shorter and I wasn't able to think of a way to do so in front of the whiteboard. So I have been thinking about this little exercise since then, and finally came up with one that is pretty elegant.

The way it works is that: *M is taken in as the *args in zip() thus unpacked as zip([0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]) .

 

Leave a Reply

Your email address will not be published. Required fields are marked *