Complex List Comprehensions Can Be Readable! | by Marcin Kozak | Apr, 2024


PYTHON PROGRAMMING

Even quite complicated Python comprehensions can be more readable than the corresponding for loops.

Towards Data Science
Python comprehensions allow for powerful computations in loops — even nested ones. Photo by Önder Örtel on Unsplash

Python comprehensions — including list, dictionary and set comprehensions as well as generator expressions — constitute a powerful Python syntactic sugar. You can read about them in the following articles:

Python comprehensions have two great advantages when compared to the corresponding for loops: they are faster and they can be much more readable.

Note the phrase “can be much more readable.” Indeed, they aren’t always more readable. This begs the following question: When are they?

It depends on you. It is you — the developer — who makes a Python comprehension readable. Sloppy implementation can destroy a comprehension’s readability, though the same can be said about for loops.

Comprehensions in Python were designed to be read in a very similar way that you read an English sentence: You can read a comprehension from left to right (or from top to bottom, if it takes several lines) just like you read an English sentence from left to right.

Many say you shouldn’t use complex comprehensions because they are difficult to read and comprehend. In this article, we’ll discuss this well-known principle — if not a myth. Unfortunately, many people strain this principle by excessively avoiding the use of Python comprehensions in situations where they could be used with success.

You can read a comprehension from left to right (or from top to bottom, if it takes several lines) just like you read an…

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here