ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 30 Jun 2021 00:39:18 +0200Index problemhttps://ask.sagemath.org/question/57817/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 ?Tue, 29 Jun 2021 22:48:32 +0200https://ask.sagemath.org/question/57817/index-problem/Answer by John Palmieri for <p>I am absolutely confused to ask a question that I think to have asked a lot of time but each time I am confused.</p>
<p>I have this simple code </p>
<pre><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
</code></pre>
<p>If I replace <code>(0..1)</code> by <code>(1..2)</code> whith the correction for the x[i], I have an error of the type <code>list index out of range</code>. Why ?</p>
https://ask.sagemath.org/question/57817/index-problem/?answer=57820#post-id-57820The 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_2Wed, 30 Jun 2021 00:39:18 +0200https://ask.sagemath.org/question/57817/index-problem/?answer=57820#post-id-57820