Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to count total number when iterating a generator?

Tags:

python

I'm always told that the enumerate built-in can be used when you need to count number and iterate at the same time.

For example this is a common idiom in Python (function gen returns a generator):

for index, item in enumerate(gen()):
    # Do something with item

# get the numbers consumed from generator
print("% number of items processed" % (index+1,))

But if the generator returns nothing? e.g. enumerate(range(0)), the index variable will be undefined.

We can define index variable before the for loop, but is there any more pythonic solution that I didn't aware of?

like image 762
yegle Avatar asked Apr 11 '14 21:04

yegle


1 Answers

enumerate(gen(), start=1) will make index start counting from 1, removing the need for index+1. Otherwise, I think what you have is already Pythonic.

index = 0
for index, item in enumerate(gen(), start=1):
    # Do something with item

print("%d number of items processed" % (index,))
like image 154
unutbu Avatar answered Nov 15 '22 00:11

unutbu