Do not promote `None` as the first argument to `filter` in documentation.

Kirill Balunov kirillbalunov at gmail.com
Tue Mar 6 10:12:21 EST 2018


2018-03-06 17:55 GMT+03:00 Chris Angelico <rosuav at gmail.com>:

> On Wed, Mar 7, 2018 at 1:48 AM, Kirill Balunov <kirillbalunov at gmail.com>
> wrote:
> > Note: For some historical reasons as the first argument you can use None
> > instead of function, in this case the identity function is assumed. That
> > is, all elements of iterable that are false are removed which is
> equivalent
> > to (item for item in iterable if item). Currently, for the same purpose
> the
> > preferred form is `filter(bool, iterable)`.
> >
>
> I'd prefer to word it something like:
>
> If the first argument is None, the identity function is assumed. That
> is, all elements of the iterable that are false are removed; it is
> equivalent to (item for item in iterable if item). It is approximately
> equivalent to (but faster than) filter(bool, iterable).
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>

I do not want to seem rude and stubborn, but how much faster is it to
highlight or emphasize it:

from random import randint
for i in [1, 10, 100, 1000, 10000, 100000]:
    ls = [randint(0,1) for _ in range(i)]
    %timeit [*filter(None, ls)]
    %timeit [*filter(bool, ls)]
    print()

272 ns ± 0.0346 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
282 ns ± 0.0714 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

283 ns ± 0.0645 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
296 ns ± 0.116 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

1.4 µs ± 1.32 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.41 µs ± 4.05 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

14.7 µs ± 40.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
14.7 µs ± 23.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

137 µs ± 186 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
137 µs ± 24.7 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

1.32 ms ± 285 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.32 ms ± 908 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

With kind regards,
-gdg



More information about the Python-list mailing list