Comprehension Scope and Name Visibility
Core idea
Scope describes where a name can be used. Ordinary comprehension iteration targets have their own scope in Python 3, so they do not overwrite a same-named variable outside. The leftmost iterable expression is evaluated in the enclosing scope; the other clauses and result expression can use comprehension-local names and accessible outer names.
The target n is local to the comprehension; the outer n remains 99.
Use an outer value
The local target n and outer factor are both available in the expression.
Compare with an explicit loop
values = [2, 5]print([values + 1 for values in values])print(values)for values in [7, 8]: passprint(values)The leftmost iterable reads the outer list. The comprehension target does not replace it; the ordinary for target does. The pass statement performs no action.
Common mistake
An iteration target introduced only inside a comprehension is not a new outer variable. Prefer distinct meaningful names to avoid confusion. This lesson covers ordinary iteration targets, not assignment expressions (:=).
Practice
Set item = "outside", build a list using item as the iteration target, and print item afterward. Repeat with an ordinary for loop and explain the difference.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Comprehension scope
Check your understanding of comprehension scope.
What is printed?
n = 10values = [n for n in [1, 2]]print(n)What is printed?
factor = 3print([n * factor for n in [2, 3]])What is printed?
a = [1, 2]print([a + 1 for a in a])print(a)How does a regular for loop differ from a comprehension iteration target in the same scope?