lambda without vars?
scarblac-spamtrap at pino.selwerd.nl
Wed Mar 15 15:10:47 CET 2000
moonseeker at my-deja.com wrote in comp.lang.python:
> Can't I use variables in a lambda definition?
> xList = [5, 10, 20, 35, 55]
> y = 50
> a = filter (lambda x: x<y, xList)
Actually, this works fine. What probably didn't work for you is using this
construct inside a function. That's because Python has only two namespaces:
the function's local namespace and the module's global namespace. In this
example, xList and y are global, so they can be used inside the lambda.
If you use this inside a function, they're part of the function's local
namespace, and the lambda has its own local namespace, so it can't access y.
Solution: include the value of y in the lambda definition, as in
a = filter (lambda x, y=y: x<y, xList)
See also the FAQ.
Remco Gerlich, scarblac at pino.selwerd.nl
Hi! I'm a .sig virus! Join the fun and copy me into yours!
More information about the Python-list