This rule raises an issue when list(), set() or dict() is unnecessarily used around a generator expression.

Why is this an issue?

Using list(), set(), or dict() around a generator expression is redundant when a corresponding comprehension can directly express the same operation. Comprehensions are clearer, more concise, and often more readable than the equivalent constructor/generator expression combination.

This principle applies to all three built-in collection types: list, set, and dict:

Exceptions

If the generator expression doesn’t filter or modify the collection, the rule does not raise. For example, list(x for x in foo) is simply copying the iterable foo into a list, which is equivalent to list(foo) and covered by a different rule.

How to fix it

Replace the collection constructor with the appropriate comprehension syntax.

Code examples

Noncompliant code example

def f(x):
    return x * 2

list(f(x) for x in range(5))  # Noncompliant

Compliant solution

def f(x):
    return x * 2

[f(x) for x in range(5)] # Compliant

Resources

Documentation