2

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
  • 115,751
  • 26
  • 228
  • 437
  • 4
    Don't mean to be rude, but reading the doc is the first thing you should do before posting here, cf [ask]. – bruno desthuilliers Mar 26 '20 at 08:01
  • Related: [What is Truthy and Falsy, in Python?](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false) – smci Mar 26 '20 at 08:04
  • Does this answer your question? [What is Truthy and Falsy? How is it different from True and False?](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false) – Tomerikoo Mar 26 '20 at 08:10

2 Answers2

4

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 and False.
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • ...
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • From the https://docs.python.org/3/library/functions.html#filter it says " If a function is None, the identity function is assumed, that is, all elements of iterable that are false are removed". but the element zero(0) in our case is not false. – Nathan Kirui Mar 26 '20 at 08:06
  • @NathanKirui as I've also linked above, 0 is also considered false; I've added another quote. – jonrsharpe Mar 26 '20 at 08:10
  • @NathanKirui note that it just says *false* as opposed to *`False`*. This means objects that are *considered* to be false (not the constant `False`), and as the quote that jon provided you have the list of those objects – Tomerikoo Mar 26 '20 at 08:16
3

The answer by @jonrsharpe explains why you get [3,1,2] instead of [3,0,1,2]. This is because 0 as well as None evaluates false-y in Python.

But in case you want the code to perform as expected, try this:

inputs = [3, 0, 1, 2, None]
print(list(filter(lambda x: x is not None, inputs)))

This should return the output as [3,0,1,2]

Hades1598
  • 320
  • 1
  • 7