# 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 + x <= -2, x >=0,x >=0]
show(Ineq)
type(Ineq)
sol0=solve_ineq([x + x <= -2, x >=0,x >=0],[x,x])
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
x_1
sage: x
x_2
sage: x
---------------------------------------------------------------------------
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 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
x_1
sage: x
x_2

more