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
:
- Use
[f(x) for x in foo]
instead of list(f(x) for x in foo)
- Use
{f(x) for x in foo}
instead of set(f(x) for x in foo)
- Use
{k: v for k, v in items}
instead of dict((k, v) for k, v in items)
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.