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?
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,))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With