This rule raises an issue when list comprehensions are used as parameters to any() or all() instead of generator expressions as this prevents any() or all() from short-circuiting.

Why is this an issue?

Using a list comprehension inside any() or all() forces the entire list to be created in memory before the check begins. This prevents the short-circuiting behavior that these functions are designed to leverage, where any() stops at the first True and all() stops at the first False.

Using a generator expression provides the same functionality while preserving the short-circuiting behavior of these functions. This could save both processing time and memory, especially for large iterables or when the condition has side effects or is computationally expensive.

How to fix it

Use a generator expression instead of a list comprehension.

Code examples

Noncompliant code example

numbers = [1, 5, 0, 10]
res_all = all([x > 2 for x in numbers])  # Noncompliant: will evaluate all numbers instead of stopping at "5"

Compliant solution

numbers = [1, 5, 0, 10]
res_all = all(x > 2 for x in numbers)  # Compliant

Resources

Documentation