Get count of iterations after for loop is completed
Get count of iterations after for loop is completed
In a python for loop, how do I get the value of i below when the loop is completed? Is there any idiomatic way to do that without defining a variable outside and loop and storing i within it in each loop run? Like some sort of finally for a for loop?
i
finally
for i, data in enumerate(somevar):
# do something
# get what i was when for loop completed here??
2 Answers
2
Do nothing. A new scope is not created by your for loop. You can access i immediately after and outside your loop:
for
i
for i, data in enumerate(somevar):
pass
print(i) # 9
See Scoping in Python 'for' loops for more detail.
i = None
0
enumerate
start
1
UnboundLocalError
i
this is interesting, loop variable usually never needed outside of the loop. why does python allow this?
– Selman Genç
Sep 5 '18 at 0:41
@SelmanGenç, See the link I just added to my answer.
– jpp
Sep 5 '18 at 0:42
i will work for what you want.
i
for loops don't have a finally block, but they do have an else which get's executed if you don't hit a break in the main body.
for
finally
else
break
for i, value in enumerate(values):
if value == some_value:
print("Found the value")
break
else:
print("Didn't find value we were looking for")
print("Went through for loop times".format(i))
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Note: If there is a possibility of the input iterable being empty, add
i = Noneor some other marker value before the loop begins (0also works, though it can be confused for "exited during the first loop" if you don't changeenumerate'sstartvalue to1); otherwise, you risk anUnboundLocalErrorif you try to useiwhen the loop never executed even once.– ShadowRanger
Sep 5 '18 at 0:24