I am Python newbie, and just become very interested in Lambda expression. The problem I have is to find one and only one target element from a list of elements with lambda filter. In theory, when the target element is found there is no sense to continue anymore.
With for loop
it is pretty simple to break
the loop, but what about by using lambda
? is it after all possible to do this? I search from Google, but did not find the expected solution
Lambda functions are syntactically restricted to return a single expression. You can use them as an anonymous function inside other functions. The lambda functions do not need a return statement, they always return a single expression.
That's not more than one return, it's not even a single return with multiple values. It's one return with one value (which happens to be a tuple).
You can use as many arguments as you want in a lambda function, but it can have only one expression. This expression is evaluated and returned as a result.
A lambda function can take any number of arguments, but can only have one expression.
From https://docs.python.org/3/library/functions.html#filter
Note that
filter(function, iterable)
is equivalent to the generator expression(item for item in iterable if function(item))
if function is notNone
and(item for item in iterable if item)
if function isNone
.
So in practice your lambda will not be applied to whole list unless you start getting elements from it. So if you Only request one item from this generator you will get your functionality.
@edit:
To request one object you'd call next(gen)
lst = [1,2,3,4,5]
print(next(filter(lambda x: x%3==0, lst)))
Would output 3
and not process anything past 3
in lst
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