Passing a parameter to filter

Fredrik Lundh fredrik at pythonware.com
Fri Apr 16 13:26:45 EDT 2004


Thomas Philips wrote:

> Now, I try to filter a range using
> >>> filter(f(k=3),range(20))

f(k=3) calls the function, so you're passing the return value to filter,
not the function itself.  that's obviously not what you want.

some alternatives:

    filter(lambda x: f(x, 3), range(20))

    [x for x in range(20) if f(x, 3)]

the lambda form creates an "anonymous function" that takes one
argument, and calls your f() function with the right arguments.

the second form is a "list comprehesion", which is a compact way
to write for-in loops.

</F>

(this reply will be followed by 20 replies pointing you to 150-line scripts
that lets you do what you want by a combination of metaclasses, byte-
code rewriting, and iterators...)







More information about the Python-list mailing list