yohhoyの日記

技術的メモをしていきたい日記

リスト内包表記と変数スコープ

プログラミング言語Pythonにおけるリストの内包表記と変数スコープの関係についてメモ。

x = 42
a = [x for x in range(1,10)]
print(x)

In Python 2.3 and later releases, a list comprehension "leaks" the control variables of each for it contains into the containing scope. However, this behavior is deprecated, and relying on it will not work in Python 3.0

http://docs.python.org/release/2.7.2/reference/expressions.html#id19

Note that the comprehension is executed in a separate scope, so names assigned to in the target list don't "leak" in the enclosing scope.

http://docs.python.org/release/3.2.2/reference/expressions.html#displays-for-lists-sets-and-dictionaries

関連URL