Here g
and h
return function object, but filter
waits an function which returns a boolean or object wich will convert as boolean . With f
it is correct for your expected output, but for g
and h
, the condition is always true
because bool(function object)
is always true
see here, a python function is a callable object.
Take:
def f(x):
return x < 5
def g(x):
return lambda: x < 5
def h(x):
return lambda x=x: x < 5
I advise to do:
ls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print([x for x in ls if f(x)]) # list comprehension
# is equivalent to filter(lambda x: x < 5, ls) iterator
# To get list :
# [x for x in filter(lambda x: x < 5, ls)]
# is equivalent to list(filter(lambda x: x < 5, ls))
Output:
[0,1,2,3,4]
To call g
to do:
g(1)() # True
Do:
print([x for x in ls if g(x)()])
Output:
[0,1,2,3,4]
To call h
to do:
h(1)() # True
or
h(1)(5) # False the second argument overrides the first one
Do:
print([x for x in ls if h(x)(x)])
# or print([x for x in ls if h(x)()])
Output:
[0,1,2,3,4]
See documentation to use filter:
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable)
is equivalent to [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
.
See documentation to use lambda expression:
lambda arguments: expression
with :
def <lambda>(arguments):
return expression