Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter mystery output

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 ?

like image 268
Darshan Chaudhary Avatar asked Dec 24 '22 14:12

Darshan Chaudhary


2 Answers

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
like image 83
Rahul Gupta Avatar answered Dec 28 '22 09:12

Rahul Gupta


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]
like image 32
Bhargav Rao Avatar answered Dec 28 '22 10:12

Bhargav Rao