I need to define some variables in Sage with 2 indices and the second index is negative. For example, Y[2, -6]. I know how to define variables with one index:

R=PolynomialRing(QQ, 'a' ,rank+1)    

Edit: I tried the following codes to define Y[i,s]:

m, n = 8, 8
Y = {(i,j): var("Y_{}{}".format(i,j),
for i in [0..m] for j in [(-2*n)..0]}

But it is said that "The name "Y_0-16" is not a valid Python identifier".

Is there some way to define Y[i,s] in Sage? Thank you very much.

  • $\begingroup$ I don't understand the purpose of the provided code and I don't understand what you mean by "index" considering the provided example. Could you clarify? $\endgroup$ – David Scholz Feb 22 at 22:30
  • $\begingroup$ @DavidScholz, thanks for your comments. I have edited the question. $\endgroup$ – LJR Feb 23 at 8:45
  • $\begingroup$ This question is likely out of scope on math stack exchange; such questions are welcome on Ask Sage. $\endgroup$ – Samuel Lelièvre Feb 23 at 18:06

This may do what you want.

sage: m, n = 8, 8
sage: Y = {(i, j): var("Y_{}_{}".format(i, str(j).replace('-', 'm')),
....:                  latex_name="Y_{{{},{}}}".format(i, j))
....:      for i in (0 .. m) for j in (-2*n .. 0)}


sage: a = Y[0, -16] * Y[2, -3]
sage: a
sage: latex(a)
{Y_{0,-16}} {Y_{2,-3}}

We replaced the "minus sign" - with an m in Python identifiers but the LaTeX name is as desired.

In a Jupyter sheet, %display latex will ensure LaTeX rendering.


Let us make a precise minimal example first.


This yields to the error as described in your question. The function "var" requires the provided name to be a valid Python identifier, thus the symbol "-" is not allowed as it is a reserved keyword.

We can check this using the isidentifier-method, which returns false if the provided String is not a valid Python identifier.

Calling the following to confirm


Of course this returns False. In general, there is no way to use "var" with invalid Python identifiers, but there might be a trick. Looking at the source code on GitHub shows that after the "isidentifier"-check (take a look at lines 888-890) the call is delegated to "SR.symbol".

Hence for avoiding the above check, we could call


which yields to


And using your provided example with SR.symbol:

m, n = 8, 8
Y = {(i,j): SR.symbol("Y_{}{}".format(i,j),latex_name="Y_{{{}{}}}".format(i,j))
for i in [0..m] for j in [(-2*n)..0]}

This yields to

{(0, -16): Y_0-16,
(0, -15): Y_0-15,
(0, -14): Y_0-14,
(0, -13): Y_0-13,
(0, -12): Y_0-12,
(0, -11): Y_0-11,


However, this might raise severe problems depending on your application and I would not necessarily recommend doing so (e.g. using this in different buildin methods will most likely yield in errors as sage does not expect this).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.