List comprehension

List comprehension

List comprehension is an important Python feature that allows you to build lists in a concise fashion. To give a simple example, the following list comprehension builds a list containing the squares of the numbers from 1 through 5:

gurobi> print [x*x for x in [1, 2, 3, 4, 5]]
[1, 4, 9, 16, 25]
A list comprehension can contain more than one for clause, and it can contain one or more if clauses. The following example builds a list of tuples containing all x,y pairs where x and y are both less than 3 and are not equal:
gurobi> print [(x,y) for x in range(3) for y in range(3) if x != y]
[(0, 1), (0, 2), (1, 0), (1, 2) (2, 0), (2, 1)]
(Details on the range function can be found here). List comprehension is used extensively in our Python examples.