On Wed, Mar 7, 2018 at 12:23 AM, Kirill Balunov <kirillbalu...@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@sikorsky:~$ python3 -m timeit '[i for i in range(1000) if i % 3]' 10000 loops, best of 5: 34.5 usec per loop rosuav@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 -- https://mail.python.org/mailman/listinfo/python-list