List comprehensions
We now introduce a very powerful feature of Python, the list comprehension. It’s not powerful because of what it can do, but because of how succinct it is. A list comprehension lets you take a list and process it in a single line. We take a look at list comprehensions, because they are so useful in processing text; for example, you can use a list comprehension to take a line of text and replace all double-spaces with single spaces, or convert all lower-case characters to upper-case characters.
List comprehensions can be applied to any iterable. An iterable is a structure that you can step through, such as a list, a string, or a tuple. The simplest form of list comprehension is this:
x =
[i
for i
in y
]
Here, x
and y
are strings (or lists). The text in bold represents Python reserved words and punctuation. The variable i
is a user-chosen variable used to step through the list. We could have used any name instead of i; it simply doesn’t matter...