User Tools

Site Tools


python3:list_comprehensions

This is an old revision of the document!


List Comprehensions

List comprehensions are used for creating lists from existing lists and other iterable structures. List comprehensions typically follow formatting similar to set-builder notation in discrete mathematics.

Syntax

Consider the following illustrative Python3 example for generating a list of squares:

>>> sq = []
>>> for i in range(10):
...  sq.append(i**2)
... 
>>> sq
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The same could be achieved in the following list comprehension1)

>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1)
Note that the list comprehension can also be constructed by considering the set-builder construction for the same example:
{n2 | nZ ∧ 0 ≤ n ≤ 9 }.
python3/list_comprehensions.1557254365.txt.gz · Last modified: 2019/05/07 13:39 by jguerin