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

15,572

Solution 1

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]

Solution 2

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)

Solution 3

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.

Share:
15,572

Related videos on Youtube

ritratt
Author by

ritratt

Updated on September 15, 2022

Comments

  • ritratt
    ritratt almost 2 years

    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?

    • NullUserException
      NullUserException
      filter() passes a single argument to your lambda, when it expects two. Using a variable won't let you get around it.
  • ritratt
    ritratt over 11 years
    Ok that makes sense. So then how do I go about writing this code, which has to return factors for a number. I want to use filter or map so that I understand it better...or at least lambda
  • NullUserException
    NullUserException over 11 years
    Of course you could optimize this to just search up to sqrt(x), and add x/n and n to the results whenever x % n == 0. It will make a difference when the numbers get larger.
  • abhay dalvi
    abhay dalvi over 5 years
    Your original problem can be solved using list comprehension as below >>> [n for n in range(10,20) for r in range(10,20) if not n%r] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>>