Iterating through a multidimensional array in Python Iterating through a multidimensional array in Python arrays arrays

Iterating through a multidimensional array in Python


It's clear you're using numpy. With numpy you can just do:

for cell in self.cells.flat:    do_somethin(cell)


If you need to change the values of the individual cells then ndenumerate (in numpy) is your friend. Even if you don't it probably still is!

for index,value in ndenumerate( self.cells ):    do_something( value )    self.cells[index] = new_value


Just iterate over one dimension, then the other.

for row in self.cells:    for cell in row:        do_something(cell)

Of course, with only two dimensions, you can compress this down to a single loop using a list comprehension or generator expression, but that's not very scalable or readable:

for cell in (cell for row in self.cells for cell in row):    do_something(cell)

If you need to scale this to multiple dimensions and really want a flat list, you can write a flatten function.