This question already has an answer here:
- Transpose list of lists 10 answers
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:
Example:
If you need the result to be the list of lists, not the list of tuples, you can use list comprehension:
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):
zip
is the right way to do this, as shown by aga.But if you want to know why your original code wasn't working:
There are two clear problems here, and likely two others. (Since you didn't show us enough of the code or data to be sure, I can't guarantee the two likely ones.)
Presumably
results
looks something like this:When you do
for i in results
, that meansi
will be each element in results—that is, it will be[1, 2, 3]
, and then[4, 5, 6]
. You can't use a list as an index into a list, so this is guaranteed to give you aTypeError: list indices must be integers, not list
.To fix this, you need:
… or …
Next,
results[j][i]
is guaranteed to raiseIndexError: list index out of range
, becausei
is each row number, but you're trying to use it as a column number. If you're iterating over the rows and columns ofresults
, you want this:Next, unless you pre-filled
rotated
with 3 lists, each of which was pre-filled with 2 objects of some kind, you're going to get anIndexError: list assignment index out of range
.To fix this, you need to pre-fill
rotated
, something like this:… or …
Finally, I'll bet
numCenturies
is 3, in which case you'll get anotherIndexError: list index out of range
as soon asj
reaches2
. The simplest thing to do here is to just use the length of the row; there's no chance of an off-by-one error that way.Putting it all together:
But in general, Python gives you easier ways to do things than pre-creating arrays and looping over indices to fill in the values. You can use
append
—or, better, a list comprehension. Or, even better, find a higher-level way to write your use, like a single call tozip
.http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html