Loop Variables Leaking Out!

Does anyone have a sealant? My loop variables are leaking out.

1.

Can you predict the output of this code?

for x in range(7):
if x == 6:
print(x, ': for x inside loop')
print(x, ': x in global')

But x was never defined outside the scope of for loop…

2.

This time, let’s initialize x first.

x = -1
for x in range(7):
if x == 6:
print(x, ': for x inside loop')
print(x, ': x in global')

3.

Let’s try something new now.

⚠️ The following code is meant for Python 2.x versions.

x = 1
print([x for x in range(5)])
print(x)

4.

Let’s run the above code in Python 3.

⚠️ The following code is meant for Python 3.x versions.

x = 1
print([x for x in range(5)])
print(x)

Explanation

  • In Python, for-loops use the scope they exist in and leave their defined loop-variable behind in the surrounding scope. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.

  • The differences in outputs of the Python 2.x and Python 3.x interpreters for the list comprehension example can be explained by following the change documented in the What’s New In Python 3.0 changelog:




“List comprehensions no longer support the syntactic form [... for var in item1, item2, ...]. Use [... for var in (item1, item2, ...)] instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a list() constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.”