R Doolabh - 7 months ago 79
Python Question

# How to I invert a 2d list in python

I have a 2d list like this:

``````   1   2   3

4   5   6
``````

and I want to make this:

``````   1   4

2   5

3   6
``````

I've tried to do a for loop and switch each value but I keep getting an index out of bound error. Here's what I have:

``````for i in results:
for j in range(numCenturies):
rotated[i][j] = results [j][i]
``````

From python documentation on zip function:

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

Example:

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

If you need the result to be the list of lists, not the list of tuples, you can use list comprehension:

``````[list(x) for x  in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])] # returns [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
``````

If all your variables are stored in one 2d list, and you want it pass it into zip function, you can use the following (I'll call it the star notation, because I can't remember the proper English term for it):

``````results = [[1, 2, 3], [4, 5, 6]]
zip(*results) # returns [(1, 4), (2, 5), (3, 6)]
``````
Source (Stackoverflow)