loops – Iterating over a 2 dimensional python list

loops – Iterating over a 2 dimensional python list

same way you did the fill in, but reverse the indexes:

>>> for j in range(columns):
...     for i in range(rows):
...        print mylist[i][j],
... 
0,0 1,0 2,0 0,1 1,1 2,1
>>> 

This is the correct way.

>>> x = [ [0,0, 0,1], [1,0, 1,1], [2,0, 2,1] ]
>>> for i in range(len(x)):
        for j in range(len(x[i])):
                print(x[i][j])


0,0
0,1
1,0
1,1
2,0
2,1
>>> 

loops – Iterating over a 2 dimensional python list

Use zip and itertools.chain. Something like:

>>> from itertools import chain
>>> l = chain.from_iterable(zip(*l))
<itertools.chain object at 0x104612610>
>>> list(l)
[0,0, 1,0, 2,0, 0,1, 1,1, 2,1]

Leave a Reply

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