3

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
noumenal
  • 1,077
  • 2
  • 16
  • 36

1 Answers1

3

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • This works! So close... I had tried `row[col]` without success. – noumenal Mar 29 '16 at 10:17
  • 1
    @noumenal Yup, again the same thing :-) first value is the index. So `row[col]` tries to subscript a number. That is why you would have received an error. But, try to use List Comprehension as much as possible. – thefourtheye Mar 29 '16 at 10:19
  • I had been looking for the docs on this, but was not aware what the concept was called. It seems very flexible and Pythonic. – noumenal Mar 29 '16 at 11:16
  • 1
    @noumenal Do you mean you were looking for the List Comprehension? – thefourtheye Mar 29 '16 at 11:41
  • Yes. The thing that is holding me back from List Comprehension is that I need to heurestically generate and compare each integer with the previous one (`i != i_matrix[r][c-1]`) and the one above (`i != i_matrix[r-1][c]`). I guess `itertools.takewhile()` would be a possible solution, but I don't know how to refer to `i`. – noumenal Mar 29 '16 at 11:45
  • 1
    @noumenal LCs are used to create new lists based on only the current information. If you need past information, you can better write it with normal loops itself. Make sure that the code is readable and easily understandable for the future you ;-) – thefourtheye Mar 29 '16 at 11:49