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
From https://docs.python.org/3/library/functions.html#filter
Note that filter(function, iterable)
is equivalent to the generatorexpression (item for item in iterable if function(item))
if functionis not None
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