Checks for unnecessary list comprehensions passed to any and all.
Why is this bad?
any and all take any iterators, including generators. Converting a generator to a list
by way of a list comprehension is unnecessary and reduces performance due to the
overhead of creating the list.
For example, compare the performance of all with a list comprehension against that
of a generator (~40x faster here):
In [1]: %timeit all([i for i in range(1000)])
8.14 µs ± 25.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
In [2]: %timeit all(i for i in range(1000))
212 ns ± 0.892 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
An optimization recommended by
ruff
.%
ruff --select=C419 --fix .
%
ruff rule C419
unnecessary-comprehension-any-all (C419)
Derived from the flake8-comprehensions linter.
Autofix is always available.
What it does
Checks for unnecessary list comprehensions passed to
any
andall
.Why is this bad?
any
andall
take any iterators, including generators. Converting a generator to a list by way of a list comprehension is unnecessary and reduces performance due to the overhead of creating the list.For example, compare the performance of
all
with a list comprehension against that of a generator (~40x faster here):Examples
Use instead: