Inspired by the construction in this answer, I am trying to do the following:
values = range(3)
vector = np.random.randint(3, size=(5,))
f = lambda x: x in values
result = [f(a) for a in values]
but I get global name 'values' is not defined
.
I get the same error if I try the solution that I linked to above, i.e.:
A = [[0,1,2], [1,2,3], [2,3,4]]
v = [1,2]
B = [map(lambda val: val in v) for a in A]
Did Python change since that solution was posted? (I am working with 2.7.4). If so, how can I access an external variable within a lambda function? Should I declare it as global? pass it as another input?
Update 1:
I am only noticing this problem within an embedded shell in IPython (1.0).
Update 2:
There is an IPython ticket on GitHub on the topic, but it's unclear if the problem has been solved.
Update 3(Not from the OP):
The error is re-produceable in django's shell (thanks @Ashwini)
$ ./manage.py shell
Python 2.7.4 (default, Apr 19 2013, 18:32:33)
Type "copyright", "credits" or "license" for more information.
IPython 0.13.2 -- An enhanced Interactive Python.
In [1]: import numpy as np
In [2]: values = range(3)
In [3]: vector = np.random.randint(3, size=(5,))
In [4]: f = lambda x: x in values
In [5]: result = [f(a) for a in values]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 result = [f(a) for a in values]
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <lambda>(x)
----> 1 f = lambda x: x in values
NameError: global name 'values' is not defined
In [6]: values
Out[6]: [0, 1, 2]