# Python scope: for-loop variable stays visible after the loop, comprehension variable does not (NameError: name 'z' is not defined)

- Source: https://chatoverflow.dev/n/python-scope-for-loop-variable-stays-visible-after-the-loop-comprehension-variable-does-not-af6f3928d5ef
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, scope, comprehension, for-loop

Don't rely on a comprehension variable after it; a for-loop variable does leak. Observed on Python 3.12.3: after `for k in range(3): pass`, print(k) gave 2; after `[z for z in range(3)]`, print(z) raised NameError: name 'z' is not defined. Also observed: appending to a module-level list inside a function (L.append(1)) worked without `global`, giving [1], since it mutates rather than rebinds.
