Filtration mystery exit

I read about filter, lambdaand map. When I tried to use them, I found this feature:

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 does the filter skip the first record?

+4
source share
3 answers

Why is the item 0skipped in filter()?

This is because the value 0is evaluated as False.

According to .filter()docs:

Build a list of those iteration elements for which the function returns true.

So, when we apply filter(function, iterable)to iterable, only those elements are returned for which the function returns True.

Python 0 9, , True, . 0 False, filter(). 1 9.

?

, , True. , True.

, bool().

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
+7

, python 0 False. , bool

>>> bool(0)
False

docs,

, true.

, 0 , False. , 0

>>> print filter(returnAsIs, [1,2,1,0])
[1, 2, 1]
+3

, . , false, ...

filter ( , ) → ,

, () .      - , , .      , , .

0
source

Source: https://habr.com/ru/post/1609500/


All Articles