10.3 Comprehensions
Comprehensions offer simple, but powerful, syntax, allowing us to transform or filter an iterable object in as little as one line of code. The resultant object can be a perfectly normal list, set, or dictionary, or it can be a generator expression that can be efficiently consumed while keeping just one element in memory at a time.
10.3.1 List comprehensions
List comprehensions are one of the most powerful tools in Python, so people tend to think of them as advanced. They’re not. Indeed, we’ve taken the liberty of littering previous examples with comprehensions, assuming you would understand them. A comprehension is fundamental to Python; it can handle many of the most common operations in application software.
Let’s have a look at one of those common operations: namely, converting a list of items into a list of derived items. Specifically, let’s assume we just read a list of strings from a file...