2

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?

for i, data in enumerate(somevar):
    # do something
# get what i was when for loop completed here??
jpp
  • 159,742
  • 34
  • 281
  • 339
Gaurav
  • 1,095
  • 10
  • 19

2 Answers2

4

Do nothing. A new scope is not created by your for loop. You can access i immediately after and outside your loop:

for i, data in enumerate(somevar):
    pass

print(i)  # 9

See Scoping in Python 'for' loops for more detail.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • 8
    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 05 '18 at 00:24
  • this is interesting, loop variable _usually_ never needed outside of the loop. why does python allow this? – Selman Genç Sep 05 '18 at 00:41
2

i will work for what you want.

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 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))
Batman
  • 8,571
  • 7
  • 41
  • 80