I was reading about filter
, lambda
and map
. When I tried using them, I found this peculiarity :
def returnAsIs(element):
return element
print range(10)
print filter(returnAsIs, range(10))
print map(lambda x : x, range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Why is filter omitting the first entry ?
Why the element 0
gets skipped in filter()
?
This is happening because value 0
evaluates to False
.
As per the .filter()
docs:
Construct a list from those elements of iterable for which function returns true.
So, when we apply filter(function, iterable)
to an iterable
, only those elements are returned for which the function returns True
.
When Python iterated over the elements from 0
to 9
, it checks which element evaluates to True
and only those elements are returned. Now, 0
evaluates to False
so this value is not returned by filter()
. Only the elements from 1
to 9
are returned.
How to check the boolean-ness of an element?
Since your function is returning the element as it is, we need to check which elements evaluates to True
. Only those elements will be returned which evaluates to True
.
To check for the boolean-ness, we can use the bool()
function.
In [1]: for x in range(10):
...: print x, bool(x)
...:
0 False # boolean-ness of '0' is False
1 True
2 True
3 True
4 True
5 True
6 True
7 True
8 True
9 True
This is because python treats 0
as False. You can check this out using the function bool
>>> bool(0)
False
When you read from the docs,
Construct a list from those elements of iterable for which function returns true.
Hence 0
is not returned after the filter function as the value evaluates to False
. Similar is the case when you have 0
any where in the list
>>> print filter(returnAsIs, [1,2,1,0])
[1, 2, 1]
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