1

Unlike other languages like c, c++ where the scope of the variables stay inside the loop. Eg.

for(int i=0; i<5; i++)
{
    do stuff;
}

i+=1  // raises error as i is not initialised.

where as the same code works in python

for i in range(5)
    do stuff

i+=1  # doesn't raise error as i is initialised.

Though this can be helpful at times, sometimes it is a pain as even though rarely I use variable names like i, key, value yet again in the code after the loop without facing any explicit error.

Is there a more pythonic way than using del i after the loop to avoid the above issues?

EDIT: This question has been marked duplicate of Short description of the scoping rules? which I had seen ages ago. That thread describes how scoping works in python whereas my question is totally different. Please unmark this as a duplicate.

markroxor
  • 5,928
  • 2
  • 34
  • 43

1 Answers1

0

In Python3, list comprehension may be one answer...?

[print(i) for i in range(5)]
print(i)

>> 0
1
2
3
4

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-598b4fd0c0c5> in <module>()
1 [print(i) for i in range(5)]
----> 2 print(i)

NameError: name 'i' is not defined
greentec
  • 2,130
  • 1
  • 19
  • 16