osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


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