Sokunthaneth Chhoy
Sokunthaneth Chhoy

Reputation: 126

filter and lambda: passing more than one argument?

I try to print a list of number that are divisible by given number. However, the console said:

lambda>() takes exactly 2 arguments (1 given)

Code:

inp1 = int(input("Enter a number: "))
inp2 = int(input("Enter a divisor: "))

result = list(filter(lambda x, inp2: x % inp2 == 0, range(inp2, inp1)))
print("Numbers divisible by", inp2, "are", result)

How should I fix this by keep using lambda and filter?

Upvotes: 1

Views: 1729

Answers (2)

Ludisposed
Ludisposed

Reputation: 1769

Omit the inp2 after the lambda x to make it working again. The lambda was expecting the inp2 as an argument.

#inp1 = int(input("Enter a number: "))
#inp2 = int(input("Enter a divisor: "))
inp1 = 10
inp2 = 2

result = list(filter(lambda x: x % inp2 == 0, range(inp2, inp1)))
print("Numbers divisible by", inp2, "are", result)

output = Numbers divisible by 2 are [2, 4, 6, 8]

Upvotes: 0

martineau
martineau

Reputation: 123393

The simplest fix in the case is to give the second argument a default value:

#inp1 = int(input("Enter a number: "))
#inp2 = int(input("Enter a divisor: "))
inp1 = 42
inp2 = 6

result = list(filter(lambda x, inp2=inp2: x % inp2 == 0, range(inp2, inp1)))
print("Numbers divisible by", inp2, "are", result)

Output:

Numbers divisible by 6 are [6, 12, 18, 24, 30, 36]

Upvotes: 1

Related Questions