Filter Content By
Version
Languages

The tuplelist class

The next important item we would like to discuss is the tuplelist class. This is a custom sub-class of the Python list class that is designed to allow you to efficiently build sub-lists from a list of tuples. To be more specific, you can use the select method on a tuplelist object to retrieve all tuples that match one or more specified values in specific fields.

Let us give a simple example. We'll begin by creating a simple tuplelist (by passing a list of tuples to the constructor):

gurobi> l = tuplelist([(1, 2), (1, 3), (2, 3), (2, 4)])

To select a sub-list where particular tuple entries match desired values, you specify the desired values as arguments to the select method. The number of arguments to select is equal to the number of entries in the members of the tuplelist (they should all have the same number of entries). You can provide a list argument to indicate that multiple values are acceptable in that position in the tuple, or a '*' string to indicate that any value is acceptable.

Each tuple in our example contains two entries, so we can perform the following selections:

gurobi> print(l.select(1, '*'))
<gurobi.tuplelist (2 tuples, 2 values each):
( 1 , 2 )
( 1 , 3 )
>
gurobi> print(l.select('*', 3))
<gurobi.tuplelist (2 tuples, 2 values each):
( 1 , 3 )
( 2 , 3 )
>
gurobi> print(l.select('*', [2, 4]))
<gurobi.tuplelist (2 tuples, 2 values each):
( 1 , 2 )
( 2 , 4 )
>
gurobi> print(l.select(1, 3))
<gurobi.tuplelist (1 tuples, 2 values each):
( 1 , 3 )
>
gurobi> print(l.select('*', '*'))
<gurobi.tuplelist (4 tuples, 2 values each):
( 1 , 2 )
( 1 , 3 )
( 2 , 3 )
( 2 , 4 )
>


You may have noticed that similar results could have been achieved using list comprehension. For example:

gurobi> print(l.select(1, '*'))
<gurobi.tuplelist (2 tuples, 2 values each):
( 1 , 2 )
( 1 , 3 )
>
gurobi> print([(x,y) for x,y in l if x == 1])
[(1, 2), (1, 3)]

The problem is that the latter statement considers every member in the list, which can be quite inefficient for large lists. The select method builds internal data structures that make these selections quite efficient.

Note that tuplelist is a sub-class of list, so you can use the standard list methods to access or modify a tuplelist:

gurobi> print(l[1])
(1,3)
gurobi> l += [(3, 4)]
gurobi> print(l)
<gurobi.tuplelist (5 tuples, 2 values each):
( 1 , 2 )
( 1 , 3 )
( 2 , 3 )
( 2 , 4 )
( 3 , 4 )
>