Skip to content

Set Comprehension

Sourcery refactoring id: set-comprehension

Description:

Replaces sets created with for loops with set comprehensions

Before:

cubes = set()
for i in range(20):
    cubes.add(i**3)

After:

cubes = {i**3 for i in range(20)}

Explanation:

A set comprehension can create the set on one line, cutting out the clutter of declaring an empty set and then adding values.

Turning three lines of code into one is a definite win - it means less scrolling back and forth when reading methods and helps keep things manageable.

Squeezing code onto one line can make it more difficult to read, but for comprehensions this isn't the case. All of the elements that you need are nicely presented, and once you are used to the syntax it is actually more readable than the for loop version.

Another point is that the assignment is now more of an atomic operation - we're declaring what cubes is rather than giving instructions on how to build it. This makes the code read like more of a narrative, since going forward we will care more about what cubes is than the details of its construction.

Finally comprehensions will usually execute more quickly than building the collection in a loop, which is another factor if performance is a consideration.