いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Pythonメモ-46 (2.x系と3.x系で内包表記内の変数のスコープが違う) (python2, python3, listcomp, 内包表記, 変数スコープ)

概要

pythonに慣れている人は当然な知識なのかもしれませんが、自分用に忘れない内にメモメモ。

Python 2.x 系と python 3.x 系では、内包表記で使用する一時変数のスコープが違うんですね。

python 2.x 系

$ activate py2

(py2) $ python --version
Python 2.7.14 :: Anaconda, Inc.

(py2) $ python
Python 2.7.14 |Anaconda, Inc.| (default, Nov  8 2017, 13:40:45) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
9                     # <===== えっ!!??
>>>

2.x 系だと、内包表記内でつかった一時変数が残ってる。

python 3.x 系

$ activate py3

(py3) $ python --version
Python 3.6.3 :: Anaconda, Inc.

(py3) $ python
Python 3.6.3 |Anaconda, Inc.| (default, Nov  8 2017, 15:10:56) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x                     # <===== 存在しない。(想定通り)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>>

3.x 系だと、想定通りの挙動になっている。


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。