Nathan Kirui :
As per definition, the None keyword is used to define a null value, or no value at all. But why does:
inputs = [3, 0, 1, 2, None]
print(list(filter(None, inputs)))
return this list [3,1,2]
and not [3,0,1,2]
?
jonrsharpe :
Per the filter
docs:
If function is
None
, the identity function is assumed, that is, all elements of iterable that are false are removed.
The identity function is basically:
def identity(something):
return something
so filtering on this means that any value that evaluates false-y will be excluded from the output.
Then if you look at truth-value testing you can see that, as well as None
, 0
evaluates false-y in Python:
Here are most of the built-in objects considered false:
- constants defined to be false:
None
andFalse
.- zero of any numeric type:
0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
- ...
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=360589&siteId=1