By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,548 Members | 1,496 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,548 IT Pros & Developers. It's quick & easy.

Passing a parameter to filter

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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...)


Jul 18 '05 #2

P: n/a
"Fredrik Lundh" <fr*****@pythonware.com> 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
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.