Hone

Lessons · Python · comprehension variables

A comprehension keeps its variable to itself

In Python 3 the loop variable of a comprehension lives inside it. After [x for x in range(3)], x outside is whatever it was before, or undefined.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Old tutorials show the variable leaking, and code that depended on it broke in the move to Python 3. Knowing the scope stops a class of 'where did x go' confusions.

How to think about it

Treat a comprehension like a small function: it can read outer names, but its own loop variable does not escape. If you need the last value, use a normal for loop.

Worked example

x = "outer"
A name outside.
squares = [x * x for x in range(3)]
The x inside is a different x.
print(squares)
[0, 1, 4].
print(x)
outer: untouched.
for y in range(3):
A plain loop.
    pass
Does nothing.
print(y)
2: a plain for loop does leave its variable behind.

Your turn

Total of the even numbers, without leaking n.

total = sum(n for n in nums if n % 2 == )

The trap

The loop variable of a comprehension is private, but the iterable expression is evaluated in the outer scope. [y for y in x] reads x from outside.

Practise comprehension variables on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.