List comprehensions
Those of you who have taken some advanced math courses may be familiar with set builder notation.
This is a way of specifying a subset of a known set determined by some property.
For example if you want to talk about the subset of integers that are even, you could describe this as:
This says "The set of all in such that 2 divides ."
The basic form of the statment is
Python has syntax for this called "list comprehension" syntax. (The word comprehension comes from its use in set theory. )
The form of the Python syntax is:
where S is any container (list, set, etc.) and C(a)
is some function returning True or False.
Mappings and transformations
List comprehension notation can also be used to transform each element in a list.
The basic form is:
where is any function.
Here are some examples.
All together now
You can of course do a transformation and a filter at the same time.
That is, you can do commands like:
Here are some examples.
Dictionary comprehensions
You can use notation much like list comprehension notation to initialize a dictionary.
Set comprehensions
Similarly you can select items from a set.