Passing a parameter to filter

Discussion in 'Python' started by Thomas Philips, Apr 16, 2004.

  1. To experiment with filtering, I define a function f(x,k) as follows
    >>> def f(x,k=2):

    return x%k==0

    I can check that it works by typing
    >>> f(10,3)

    False

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


    Traceback (most recent call last):
    File "<pyshell#16>", line 1, in -toplevel-
    filter(f(k=3),range(20))
    TypeError: f() takes at least 1 non-keyword argument (0 given)

    I next try
    >>> filter(f(3),range(20))


    Traceback (most recent call last):
    File "<pyshell#17>", line 1, in -toplevel-
    filter(f(3),range(20))
    TypeError: 'bool' object is not callable

    But, as k defaults to 2, I get exactly what I expect from
    >>> filter(f,range(20))

    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    >>>


    What's wrong with my syntax when passing the parameter k=3?

    Sincerely

    Thomas Philips
    Thomas Philips, Apr 16, 2004
    #1
    1. Advertising

  2. 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...)
    Fredrik Lundh, Apr 16, 2004
    #2
    1. Advertising

  3. "Fredrik Lundh" <> writes:

    > filter(lambda x: f(x, 3), range(20))
    >
    > [x for x in range(20) if f(x, 3)]
    >


    > </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...)


    In your list you forgot the additional 20 replies talking about currying
    (and the replies to them that currying is something different)

    Thomas
    Thomas Heller, Apr 16, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jay
    Replies:
    1
    Views:
    19,223
  2. Replies:
    0
    Views:
    345
  3. Vili
    Replies:
    0
    Views:
    693
  4. zax75
    Replies:
    1
    Views:
    1,077
  5. Mister B
    Replies:
    8
    Views:
    518
    Nick Keighley
    Aug 26, 2010
Loading...

Share This Page