Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to break from lambda when the expected result is found

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

like image 971
Rui Avatar asked Sep 02 '16 11:09

Rui


People also ask

Can Lambda return anything?

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.

Can Lambda return 2 values?

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).

How many arguments can be passed to Lambda?

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.

Can Lambda take only one input?

A lambda function can take any number of arguments, but can only have one expression.


1 Answers

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 not None and (item for item in iterable if item) if function is None.

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

like image 149
Tomasz Plaskota Avatar answered Oct 13 '22 09:10

Tomasz Plaskota