Skip to content

Collection to Comprehension

Sourcery refactoring id: collection-builtin-to-comprehension

Description:

Use list, set or dictionary comprehensions directly instead of calling list(), dict() or set()

Before:

squares = list(x * x for x in y)
squares = set(x * x for x in y)
squares = dict((x, x * x) for x in xs)

After:

squares = [x * x for x in y]
squares = {x * x for x in y}
squares = {x: x * x for x in xs}

Explanation:

The Pythonic way to create a list, set or dictionary from a generator is to use comprehensions.

Using the comprehensions rather than the methods is slightly shorter, and the dictionary comprehension in particular is easier to read in comprehension form.