Do not promote `None` as the first argument to `filter` in documentation.
2018-03-06 13:18 GMT+03:00 Chris Angelico <rosuav at gmail.com>:
> The identity function is:
> filter(lambda x: x, range(10))
> How is it consistent with truthiness? Exactly the same way the
> underlying object is. There's no requirement for the predicate
> function to return True or False - it's perfectly acceptable, for
> instance, to do this:
> filter(lambda x: x % 3, range(10))
> to eliminate all multiples of three.
Yes there is no reason to return True and False, but in the case of `None`
and `bool` under the hood there will be no difference and the form with
`bool` is much more readable.
> That said, though, any use of filter() that involves a lambda function
> should probably become list comps or genexps, so filter itself should
> only be used when there really IS a pre-existing function that does
> the job.
Filter is generally faster than list comprehension or generators.
%timeit [*filter(lambda x: x % 3, range(1000))]
100 ?s ? 16.4 ns per loop (mean ? std. dev. of 7 runs, 10000 loops each)
f = lambda x: x % 3
%timeit [*(f(i) for i in range(1000))]
132 ?s ? 73.5 ns per loop (mean ? std. dev. of 7 runs, 10000 loops each)
%timeit [f(i) for i in range(1000)]
107 ?s ? 179 ns per loop (mean ? std. dev. of 7 runs, 10000 loops each)
> So, for instance, you could strip out every occurrence of the
> string "0" with:
> filter(int, list_of_strings)
> And that still depends on the normal Python rules for boolification.
> If that's valid, then it should be just as viable to say
> "filter(identity-function, ...)", which is spelled "filter(None,