Complicated Listing Comprehensions Can Be Readable! | by Marcin Kozak | Apr, 2024


PYTHON PROGRAMMING

Even fairly difficult Python comprehensions will be extra readable than the corresponding for loops.

Python comprehensions enable for highly effective computations in loops — even nested ones. Photograph by Önder Örtel on Unsplash

Python comprehensions — together with listing, dictionary and set comprehensions in addition to generator expressions — represent a strong Python syntactic sugar. You’ll be able to examine them within the following articles:

Python comprehensions have two nice benefits when in comparison with the corresponding for loops: they’re sooner and they are often way more readable.

Notice the phrase “will be way more readable.” Certainly, they aren’t all the time extra readable. This begs the next query: When are they?

It is determined by you. It’s you — the developer — who makes a Python comprehension readable. Sloppy implementation can destroy a comprehension’s readability, although the identical will be stated about for loops.

Comprehensions in Python have been designed to be learn in a really related approach that you just learn an English sentence: You’ll be able to learn a comprehension from left to proper (or from high to backside, if it takes a number of traces) similar to you learn an English sentence from left to proper.

Many say you shouldn’t use complicated comprehensions as a result of they’re tough to learn and comprehend. On this article, we’ll talk about this well-known precept — if not a fable. Sadly, many individuals pressure this precept by excessively avoiding using Python comprehensions in conditions the place they might be used with success.

You’ll be able to learn a comprehension from left to proper (or from high to backside, if it takes a number of traces) similar to you learn an…

Leave a Reply

Your email address will not be published. Required fields are marked *