PYTHON PROGRAMMING
Even fairly sophisticated Python comprehensions will be extra readable than the corresponding for loops.
Python comprehensions — together with checklist, 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 quicker 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 relies on 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 strains) 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 troublesome 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 may very well 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 strains) similar to you learn an…