A convenient way to build up lists is by using the list comprehension construct, possibly with a condition inside. The syntax of a list comprehension is:
[<expr> for <variable> in <list>]
or more generally:
[<expr> for <variable> in <list> if <condition>]
Here are some examples:
L = [2, 3, 10, 1, 5] L2 = [x*2 for x in L] # [4, 6, 20, 2, 10] L3 = [x*2 for x in L if 4 < x <= 10] # [20, 10]
It is possible to have several for loops inside a list comprehension:
M = [[1,2,3],[4,5,6]] flat = [M[i][j] for i in range(2) for j in range(3)] # returns [1, 2, 3, 4, 5, 6]
This is of particular interest when dealing with arrays; see Section 3.2: A quick glance at the concept of arrays.
List comprehension is closely related to the mathematical notation for sets. Compare and L2 = [2*x for x in L]. One big difference though is that lists are ordered while sets aren't; see...