Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is lambda asking for 2 arguments despite being given 2 arguments?

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?

like image 254
ritratt Avatar asked Oct 05 '12 18:10

ritratt


3 Answers

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]
like image 163
Zaur Nasibov Avatar answered Oct 23 '22 10:10

Zaur Nasibov


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)
like image 39
Tagar Avatar answered Oct 23 '22 11:10

Tagar


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.

like image 28
Fred Avatar answered Oct 23 '22 11:10

Fred