4

Is it safe to read loop variable after loop (using Python 2)? My purpose is to check how many iterations in the loop are done.

Here is code to show the idea:

a=[1,2,3,4,5]

for i in range(len(a)):
    if a[i] == 2:
        break

print i # output is 1, is it safe to read i here?
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Lin Ma
  • 9,739
  • 32
  • 105
  • 175

2 Answers2

2

Yes, it is fine to read it there. This is because when you create a for loop, internally, it has a mechanism to create the indexer for you (in your case being i) and then increases it one by one by assigning new value to it every time. Thus, you can use the i after the for loop. Thus after:

a=[1,2,3,4,5]

for i in range(len(a)):
    if a[i] == 2:
        break    

i isn't really dropped. To drop i, you can use del keyword:

a=[1,2,3,4,5]

for i in range(len(a)):
    if a[i] == 2:
        break    

del i #deleted here

print i # now this will give you error!

While to replace is, you just simply need to redefine it:

a=[1,2,3,4,5]

for i in range(len(a)):
    if a[i] == 2:
        break    

i = [] #now this is a list, not an integer anymore

print i # now this will give you different result: []

Similarly, for example, if you create a list in an if block:

if i == 0: #suppose you really enter this block
   a = [] #a is created here

a.append(b) #but a can be used here, assuming the previous if is really entered

This is just how Python works.

Some related posts:

Community
  • 1
  • 1
Ian
  • 30,182
  • 19
  • 69
  • 107
  • Thanks Ian, vote up. :) What is the life scope of i? Even after the loop? – Lin Ma Mar 07 '16 at 04:20
  • 1
    @LinMa yes, it is unlike compiled programming language like C#, once created the variable is there till you replace it or drop it. This is not the same when the variable is created inside a `def` scope though, the variable will only last within the `def` – Ian Mar 07 '16 at 04:22
  • 2
    Another way the variable goes away is when it goes out of scope. – mprat Mar 07 '16 at 04:23
  • Thanks Ian, what do you mean "till you replace it or drop it"? An example is appreciated? – Lin Ma Mar 07 '16 at 04:27
  • Thanks @mprat, what is the scope here? – Lin Ma Mar 07 '16 at 04:27
  • 1
    @LinMa OK, answer updated to also address your questions in comments. :) – Ian Mar 07 '16 at 04:31
  • 1
    @DSM thanks for the correction, phrase removed. – Ian Mar 07 '16 at 04:33
  • Thanks Ian, mark your reply as an answer. :) – Lin Ma Mar 07 '16 at 04:57
  • @LinMa great! thanks! :) simply check out the [link](http://stackoverflow.com/questions/35618307/how-to-transform-string-into-dict/35618686#35618686) I gave you for further understanding on how `for` loop works. – Ian Mar 07 '16 at 05:31
  • Important caveat: `i` is bound after the loop **as long as the loop goes through at least one iteration**. Otherwise, it will be unbound and accessing it will raise a `NameError`. – dlukes Feb 07 '23 at 13:55
1

You could do it, and it would be fine to do so, since the value of i in this case only gets incremented before the execution of the internal loop. It would make this code a bit harder to read, but it would get the job done. The variable i is created in the same scope as the for loop. If the example code you gave is the entire file, then i would go out of scope when the file exists. If the code example you gave was inside a function, i would be created inside the function, then go out of scope when the function returns / exits.

An alternate way of doing this would be to use the for... in construction for loops in Python, together with the zip method, and keep a variable:

for element, i in zip(a, range(len(a)):
    if element == 2:
        index = i

Then at the end, you are setting a new variable called index and not relying on loop variables.

mprat
  • 2,451
  • 15
  • 33
  • Thanks mprat, vote up. Wondering what is the life scope of i? Even after the loop? – Lin Ma Mar 07 '16 at 04:26
  • 1
    `i` exists after the loop, yes. It is created in the same scope as the loop is created in. In your example, it goes out of scope when the program finishes (assuming this is the whole program). If this program were inside a function, `i` would go out of scope when the function exited / returned. – mprat Mar 07 '16 at 04:27
  • Thanks mprat, vote up, when i will be destroyed (I mean out of scope), from your reply, it seems i always exists? An example is appreciated. :) – Lin Ma Mar 07 '16 at 04:28