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”Description:
Section titled “Description:”Use list, set or dictionary comprehensions directly instead of calling list(), dict() or set()
Before:
Section titled “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:
Section titled “After:”squares = [x * x for x in y]squares = {x * x for x in y}squares = {x: x * x for x in xs}Explanation:
Section titled “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.