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

Chris Angelico rosuav at gmail.com
Tue Mar 6 08:51:41 EST 2018


On Wed, Mar 7, 2018 at 12:23 AM, Kirill Balunov <kirillbalunov at gmail.com> wrote:
> 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)
>

These don't do the same thing, though. A more comparable comprehension is:

[i for i in range(1000) if i % 3]

rosuav at sikorsky:~$ python3 -m timeit '[i for i in range(1000) if i % 3]'
10000 loops, best of 5: 34.5 usec per loop
rosuav at sikorsky:~$ python3 -m timeit '[*filter(lambda x: x % 3, range(1000))]'
5000 loops, best of 5: 81.1 usec per loop

And my point about comprehensions was that you do NOT use a pointless
function for them - you just have inline code. If there is a
pre-existing function, sure! Use it. But when you use filter or map
with a lambda function, you should probably use a comprehension
instead.

ChrisA



More information about the Python-list mailing list