Counting nested loop iterations

Carl Banks invalidemail at aerojockey.com
Thu Mar 16 22:15:29 CET 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

I don't know if it's kludgy, but I do prefer to set counters in the for
statement whenever I can.  If I were using 2.4, I might try writing
something like:

    for i,(animal,zoo) in enumerate((animal,zoo) for animal in zoo for
color in animal):
        pass

or maybe break it down a little for clarity:

    aciter = ((animal,zoo) for animal in zoo for color in animal)
    for i,(animal,zoo) in enumerate(aciter):
        pass

But even the clear version isn't as nearly clear and straightforward as
the nested fors with the counter.  I wouldn't forsake that clarity just
so it isn't "kludgy".


Carl Banks




More information about the Python-list mailing list