Comprehensions have their own scope:
>>> n = 4
>>> squares = [n**2 for n in range(9)]
>>> n
4
But loops do NOT have their own scope:
>>> n = 4
>>> for n in squares: ...
>>> n
81
This may seem like a gotcha, but there's a good reason for this.
For convenience, Python lacks variable declarations. Assignments "declare" implicitly. Due to this, function-level scope makes a LOT more sense in Python, so #Python's scope is function-level, not block-level.
#PythonOddity

GitHub
python-oddities/gotchas/function-scope.md at main ยท treyhunner/python-oddities
Yes this repository will be renamed soon... Contribute to treyhunner/python-oddities development by creating an account on GitHub.
