Skip to content

List Comprehension

Sourcery refactoring id: list-comprehension


Converts a for loop into a list comprehension


cubes = []
for i in range(20):


cubes = [i**3 for i in range(20)]


A list comprehension can create the list on one line, cutting out the clutter of declaring an empty list and then appending 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.