# Index problem

I am absolutely confused to ask a question that I think to have asked a lot of time but each time I am confused.

I have this simple code

x = list(var('x_%i' % i) for i in (0..1))
show(x)
Ineq = [x[1] + x[0] <= -2, x[1] >=0,x[0] >=0]
show(Ineq)
type(Ineq[0])
sol0=solve_ineq([x[0] + x[1] <= -2, x[1] >=0,x[0] >=0],[x[0],x[1]])
sol0


If I replace (0..1) by (1..2) whith the correction for the x[i], I have an error of the type list index out of range. Why ?

edit retag close merge delete

Sort by ยป oldest newest most voted

The line x = list(var('x_%i' % i) for i in (0..1)) defines x to be a list, and no matter what numbers you put in (m..n), lists in Python are indexed starting at 0. For example:

sage: x = list(var('x_%i' % i) for i in (1..2))
sage: x
[x_1, x_2]
sage: x[0]
x_1
sage: x[1]
x_2
sage: x[2]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-481b12fa0bac> in <module>
----> 1 x[Integer(2)]

IndexError: list index out of range


That is, x[0] refers to the 0th element of the list x; the part of the command for i in (1..2) doesn't affect the list indexing. You could use a dictionary if you want different indexing:

sage: x = dict((i, var('x_%i' % i)) for i in (1..2))
sage: x  # the numbers 1 and 2 are the keys: the allowable indices
{1: x_1, 2: x_2}
sage: x[1]
x_1
sage: x[2]
x_2

more