An Introduction to Pythonby Guido van Rossum and Fred L. Drake, Jr. Paperback (6"x9"), 124 pages ISBN 0954161769 RRP £12.95 ($19.95) Sales of this book support the Python Software Foundation! Get a printed copy>>> |

### 5.1.4 List Comprehensions

List comprehensions provide a concise way to create lists without resorting
to use of `map()`

, `filter()`

and/or `lambda`

.
The resulting list definition tends often to be clearer than lists built
using those constructs. Each list comprehension consists of an expression
followed by a `for`

clause, then zero or more `for`

or
`if`

clauses. The result will be a list resulting from evaluating
the expression in the context of the `for`

and `if`

clauses
which follow it. If the expression would evaluate to a tuple, it must be
parenthesized.

>>> freshfruit = [' banana', ' loganberry ', 'plum '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'plum'] >>> vec = [2, 4, 6] >>> [3*x for x in vec] [6, 12, 18] >>> [3*x for x in vec if x > 3] [12, 18] >>> [3*x for x in vec if x < 2] [] >>> [[x,x**2] for x in vec] [[2, 4], [4, 16], [6, 36]] >>> [x, x**2 for x in vec] # error - need () for tuples File "<stdin>", line 1, in ? [x, x**2 for x in vec] ^ SyntaxError: invalid syntax >>> [(x, x**2) for x in vec] [(2, 4), (4, 16), (6, 36)] >>> vec1 = [2, 4, 6] >>> vec2 = [4, 3, -9] >>> [x*y for x in vec1 for y in vec2] [8, 6, -18, 16, 12, -36, 24, 18, -54] >>> [x+y for x in vec1 for y in vec2] [6, 5, -7, 8, 7, -5, 10, 9, -3] >>> [vec1[i]*vec2[i] for i in range(len(vec1))] [8, 12, -54]

List comprehensions are much more flexible than `map()`

and can be
applied to complex expressions and nested functions:

>>> [str(round(355/113.0, i)) for i in range(1,6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159']

ISBN 0954161769 | An Introduction to Python | See the print edition |