If the loop is in a list / tuple / sequence, you can use len(...)to determine how many times the loop has been executed. But when going through an iterator, you cannot.
[Update for clarity: I am thinking of single-user end iterators, where I want to do element calculations and count them at the same time.]
I am currently using an explicit counter variable, as in the following example:
def some_function(some_argument):
pass
some_iterator = iter("Hello world")
count = 0
for value in some_iterator:
some_function(value)
count += 1
print("Looped %i times" % count)
Given that "Hello world"there are 11 characters in, the expected result is here:
Looped 11 times
I also considered this shorter alternative using enumerate(...), but I don't find it clear:
def some_function(some_argument):
pass
some_iterator = iter("Hello world")
count = 0
for count, value in enumerate(some_iterator, start=1):
some_function(value)
print("Looped %i times" % count)
[ : @mata , , , , . count = 0 , for ... else ... .]
enumerate(...) , , , . , .
Pythonic ( Python 3 Python 2)?