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.

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.

Search