List comprehensions leak their loop variable in Python2: how making it be compatible with Python3

大憨熊 提交于 2019-12-05 23:07:20

The best way is usually to just not reuse variable names like that, but if you want something that gets the Python 3 behavior in both 2 and 3:

list(x for x in (1, 2, 3))

@mgilson's comment is probably the truth, but if you want to write code that works in both python2 and python3, you could wrap a generator function in a list function, Example:

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
>>> x = 'before'
>>> a = list(x for x in (1, 2, 3))
>>> x
'before'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!