Using Python, am finding it difficult to get filter() to work with lambda for cases where more than 1 argument needs to be passed as is the case in the following snippet:
max_validation = lambda x,y,z: x < y < z
sequence1 = [1,4,8]
filter(max_validation, sequence1)
It raises the following error:
TypeError: <lambda>() takes exactly 3 arguments (1 given)
Please suggest as to what am doing wrong here.
To pass multiple arguments in the lambda function, we must mention all the parameters separated by commas. Let us understand this with an example. We will create a lambda function that takes three parameters; a list and two integers.
A lambda function can have as many arguments as you need to use, but the body must be one single expression.
Given a list of numbers, find all numbers divisible by 13. We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is without a name.
A lambda function can take any number of arguments, but can only have one expression.
It's a little bit difficult to figure out exactly what you're trying to do. I'm going to interpret your question, then provide an answer. If this is not correct, please modify your question or comment on this answer.
I have sequences that are exactly three elements long. Here's one:
sequence1 = [1, 4, 8]
I want to ensure that the first element is less than the second element, which should in turn be less than the third element. I've written the following function to do so:
max_validation = lambda x, y, z: x < y < z
How do I apply this using filter
? Using filter(max_validation, sequence1)
doesn't work.
Filter applies your function to each element of the provided iterable, picking it if the function returns True
and discarding it if the function returns False
.
In your case, filter
first looks at the value 1
. It tries to pass that into your function. Your function expects three arguments, and only one is provided, so this fails.
You need to make two changes. First, put your three-element sequence into a list or other sequence.
sequences = [[1, 4, 8], [2, 3, 9], [3, 2, 3]]
max_validation = lambda x: x[0] < x[1] < x[2] and len(x) == 3
I've added two other sequences to test. Because sequences
is a list of a list, each list gets passed to your test function. Even if you're testing just one sequence, you should use [[1, 4, 8]]
so that the entire sequence to test gets passed into your function.
I've also modified max_validation
so that it accepts just one argument: the list to test. I've also added and len(x) == 3
to ensure that the sequences are only 3 elements in length
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