Skip to content

Collection to Comprehension

Sourcery refactoring id: collection-builtin-to-comprehension


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


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)


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


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.