Using filter()

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Wed Jul 19 05:52:24 EDT 2000


Larry Whitley wrote in comp.lang.python:
> I don't understand why lambda needs the second parameter.  When I experiment
> with
> 
> filter( lambda x: string.find( x, name) == 0, fileList)
> 
> in place of
> 
> filter( lambda x,sf=string.find: sf(x, name )==0, fileList )
> 
> it works as well.  I suspect that your codeing come from something more
> general.  Can you explain the reason the sf=string.find construction is
> useful in this context?

You tried this out in the global namespace, outside a function. Then it's
not needed.

Since the lambda is another function, it only sees its own namespace
and the module's global namespace, and not the namespace of the function
you define and use it in. So you have to pass variables in as default
parameters to make them visible inside the lambda...

Actually, that's not needed for string.find if string is imported globally.
But you *do* need to use "name=name" as well if name is a local variable
in a function.

The sf=string.find makes it slightly faster.
-- 
Remco Gerlich,  scarblac at pino.selwerd.nl

   This is no way to be
     Man ought to be free      -- Ted Bundy
       That man should be me



More information about the Python-list mailing list