How to make this faster

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jul 5 12:24:19 EDT 2013


On Fri, 05 Jul 2013 14:54:26 +0000, Helmut Jarausch wrote:

> On Fri, 05 Jul 2013 13:44:57 +0100, Fábio Santos wrote: May I suggest
> you avoid range and use enumerate(the_array) instead? It might be
> faster.
> 
> How does this work?
> 
> Given
> 
> Grid= [[0 for j in range(9)] for i in range(9)]

This creates a list containing nine lists, each one of which contains 0 
repeated nine times.

That can be simplified to:

grid = [[0]*9 for i in range(9)]

which will likely be faster, although for such a small number of lists 
you may not notice the difference.


> for (r,c,val) in ????(Grid) :

This causes a SyntaxError, as ???? is not legal Python code. I'm not 
really sure what you think you are trying to do here. But I think Fábio 
means that instead of writing code like this:

for r in range(9):
    for c in range(9):
        value = grid[r][c]
        ...

you should consider writing this:

for r, row in enumerate(grid):
    for c, value in enumerate(row):
        ...


-- 
Steven



More information about the Python-list mailing list