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.





Note: If there is a possibility of the input iterable being empty, add i = None or some other marker value before the loop begins (0 also works, though it can be confused for "exited during the first loop" if you don't change enumerate's start value to 1); otherwise, you risk an UnboundLocalError if you try to use i when the loop never executed even once.
– ShadowRanger
Sep 5 '18 at 0:24



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ