Learning to use list comprehensions
Let's look at list comprehensions in depth now that we've used simpler versions several times. It's a powerful-yet-simple syntax that has been in Python since version 2.0. List comprehensions are described very succinctly and with very clear examples in PEP 202 at http://www.python.org/dev/peps/pep-0202/.
Tip
A Python Enhancement Proposal (PEP) is a design document for a Python feature (or similar). Often it can be very long and technical. PEP 202 is a very straightforward PEP that is well worth reading, consisting of three paragraphs and one example block. Some other notable PEPs will be mentioned in this book and in the appendices.
Oh, and PEP 1 describes PEPs and the PEP process, of course.
A list comprehension has the following form:
[<map> for <variable> in <selection> | if <predicate>]
The map
is the item that ends up in the list. It can be the same as variable
if no transformation is to take place. It's commonly...