Search code examples
pythonlistpython-2.7enumerate

Iterate Across Columns in a List of Lists in Python


When I attempt iteration across columns in a row, the column does no change within a nested loop:

i_rows = 4
i_cols = 3
matrix = [[0 for c in xrange(i_cols)] for r in xrange(i_rows)]

for row, r in enumerate(matrix):
    for col, c in enumerate(r):
        r[c] = 1

print matrix

Observed output

[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]

Expected output

[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]

I have tried different expressions such as xrange() and len() and I am considering switching to numpy. I am a bit surprised that a two-dimensional array in Python is not so intuitive as my first impression of the language.

The goal is a two-dimensional array with varying integer values, which I later need to parse to represent 2D graphics on the screen.

How can I iterate across columns in a list of lists?


Solution

  • You just have to assign the value against the col, not c

    for row, r in enumerate(matrix):
        for col, c in enumerate(r):
            r[col] = 1               # Note `col`, not `c`
    

    Because the first value returned by enumerate will be the index and the second value will be the actual value itself.