I am learning to use the function filter
but it does not return what I expected.
def es_par(n):
if n % 2.0 == 0:
print(n, "True")
return True
else:
print("False", n)
return
lista = [1, 2, 3, 4, 5, 6]
l2 = filter(es_par, lista)
print(l2)
When I do print(l2)
it returns me:
filter object at 0x000000000B2E7908
instead of even numbers.
I guess I'm doing something wrong, but I don't know what.
In python3 many of the functional programming functions like
map()
,filter()
, etc. they do not return lists, but generators.That way the evaluation is "lazy", that is, the filter is not executed until it is really needed because you are iterating over the results. When iterating, then yes, the filter will be executed, one element at a time, for each iteration.
The advantage of a "lazy" evaluation is that it requires less memory (because it does not have to build the list with the result but returns one element at a time), in addition to allowing the creation of generators and filters capable of operating on lists potentially infinite.
In fact, in your code, you will see that the function
es_par()
does not get executed even once, because theprint()
ones it contains do not get to be seen on the screen. For it to run you have to iterate over the filter. For example like this:There you can see intermingled
print()
what the function doeses_par()
and whatprint(elemento)
the loop does.Another way to force the filter to run is to convert it to a list. Internally python will iterate over the filter and add each result to a list, to finally return the resulting list:
We see
print()
what your function did, because when you convert the filter to a list and iterate over it, it is called. Now itl2
will be a list with the result:( Note . This was not the case in python2, where functional operators returned lists, if you were reading some documentation with examples for python2, you will have to adapt them)
Update
One last detail. Anything you can do with functional programming (
map()
,reduce()
,filter()
) you can do with list comprehensions as well, and for many (including Guido, creator of Python) the syntax is much clearer.In your case, to filter the even elements with this syntax it would be:
This does give you a list. If you prefer a (lazy) generator, change the square brackets to parentheses:
Keep in mind though that once a generator runs out, it "times out". If you try again a
for e in l2
you will no longer get items. If you are going to need to use them more times it will be better to have them in a list.