A comprehension is a compact way to build a new collection from an iterable. Use one when a for loop would visit items, transform or select them, and add the results to a list, set, or dictionary. section 8.9
A list comprehension has the form `[expression for variable in iterable if condition]`. The expression produces each result; the optional `if` keeps only items that meet its condition. Square brackets make the result a list. Use braces for a set, or put `key: value` before `for` to build a dictionary. section 8.9
Transform and filter
For `x = [1, 2, 3, 4]`, `[item * item for item in x]` produces `[1, 4, 9, 16]`. Add a condition—`[item * item for item in x if item > 2]`—and the result is `[9, 16]`. The first expression replaces a loop that appends each square to a new list. section 8.9
word_count = sum(len([word for word in line.split() if word.isalpha()])
for line in lines)
In this word-count expression, the list comprehension keeps only words for which `isalpha()` is true. Its length becomes one value in an enclosing generator expression summed across the lines. section 8.13.2
Try a comprehension when a loop's job is to produce a collection. If the result is consumed by an operation such as `sum`, consider a generator expression instead: it is similar but usually uses less memory. Reading every line of a large file into a list can also be a memory concern. section 8.14 section 8.13.2





