This is my code:
filter(lambda n,r: not n%r,range(10,20))
I get the error:
TypeError: <lambda>() takes exactly 2 arguments (1 given)
So then I tried:
foo=lambda n,r:not n%r
Which worked fine. So I thought this will work:
bar=filter(foo,range(10,20))
but again:
TypeError: <lambda>() takes exactly 2 arguments (1 given)
Something similar happens for map as well. But reduce works fine. What am I doing wrong? Am I missing something crucial needed in order to use filter or map?
Why do you use 2 arguments? filter()
and map()
require a function with a single argument only, e.g.:
filter(lambda x: x >= 2, [1, 2, 3])
>>> [2, 3]
To find the factors of a number (you can substitute it with lambda as well):
def factors(x):
return [n for n in range(1, x + 1) if x % n == 0]
factors(20)
>>> [1, 2, 4, 5, 10, 20]
If you run map or filter on a key-value set, then add parentheses around (k,v), like:
.filter(lambda (k,v): k*2 + v)
Because filter
in python takes only one argument. So you need to define a lambda/function that takes only one argument if you want to use it in filter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With