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.