Skip to content

Collection to Comprehension

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: collection-builtin-to-comprehension

Section titled “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.