Counting nested loop iterations

Fredrik Lundh fredrik at pythonware.com
Thu Mar 16 15:20:08 EST 2006


Derek Basch wrote:

> What is the best way to count nested loop iterations? I can only figure
> to use an index but that seems kludgy.
>
> index = 0
> for animal in zoo:
>     for color in animal:
>         index += 1

what's kludgy with using a counter to count things ?

(the real question here is of course why you need the counter.  what's
the loop doing?  if the code you posted is all you have, you can replace
it with index = sum(len(animal) for animal in zoo), but I assume you want
to do more stuff in there...)

</F>






More information about the Python-list mailing list