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:

1 2 |
M = [[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]] MT = [[grid[j][i] for j in range(len(grid[0]))] for i in range(len(grid))] |

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.

1 |
MT = list(map(list, zip(*M))) |

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])`

.