Counting nested loop iterations

Kent Johnson kent at kentsjohnson.com
Thu Mar 16 16:01:05 EST 2006


Derek Basch wrote:
> Fredrik Lundh wrote:
>>(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>
> 
> 
> Yes, I am doing more. Your example assumes that all that animals have
> the same amount of colors.

No, it doesn't. Fredrik wrote
index = sum(len(animal) for animal in zoo)

The expression (len(animal) for animal in zoo) yields a sequence of the 
lengths of the individual animals; passing this to sum() gives the total 
count.

Kent



More information about the Python-list mailing list