How to do row-to-column transposition of data in csv table?

@Ashwini’s answer is perfect. The magic happens in

zip(*lis)

Let me explain why this works: zip takes (in the simplest case) two lists and “zips” them: zip([1,2,3], [4,5,6]) will become [(1,4), (2,5), (3,6)]. So if you consider the outer list to be a matrix and the inner tuples to be the rows, that’s a transposition (ie., we turned the rows to columns).

Now, zip is a function of arbitrary arity, so it can take more then two arguments:

# Our matrix is:
# 1 2 3
# 4 5 6
# 7 8 9

zip([1,2,3], [4,5,6], [7,8,9])

>>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

# Now it is
# 1 4 7
# 2 5 8
# 3 6 9

The problem we’re facing is that in your case, we don’t know how many arguments we want to pass to zip. But at least, we already know the arguments: they are the elements of lis! lis is a list, and each element of that list is a list as well (corresponding to one line of numbers in your input file). The * is just Pythons way of telling a function “please use the elements of whatever follows as your arguments and not the thing itself!”

So

lis = [[1,2,3], [4,5,6]]
zip(*lis)

is exactly the same as

zip([1,2,3], [4,5,6])

Congrats, now you’re a Python pro! 😉

Leave a Comment