# Creating a polynomial ring where the variables are code generated This post is a wiki. Anyone with karma >750 is welcome to improve it.

Hi, The standard way to create a multivariate polynomial ring over ZZ is as follows.

sage: R.<x,y> = PolynomialRing(ZZ)


I want to create a polynomial ring over ZZ where the variables are generated by code.

sage: n = 5
sage: lstx = list(var('x_%d' % i) for i in range(n))
sage: lstx
[x_0, x_1, x_2, x_3, x_4]


My attempts at creating the desired ring whose variables are the elements of lstx result in error. Any help will be appreciated.

edit retag close merge delete

Sort by » oldest newest most voted

You don't need variables in that sense. Note that

sage: PolynomialRing?


has very extensive documentation on constructing such rings. E.g., it has examples basically like what you want.

sage: R = PolynomialRing(ZZ, 'x', 5)
sage: R
Multivariate Polynomial Ring in x0, x1, x2, x3, x4 over Integer Ring
sage: x0
NameError: name 'x0' is not defined
sage: R.inject_variables()
Defining x0, x1, x2, x3, x4
sage: x0
x0

more You can simply pass the PolynomialRing object a list of names:

sage: n = 5
sage: xs = [var("x_%d" % i) for i in range(n)]
sage: R = PolynomialRing(ZZ, names=xs)
sage: R
Multivariate Polynomial Ring in x_0, x_1, x_2, x_3, x_4 over Integer Ring
sage: x_4
x_4
sage: x_4 in R
True


In practice you're probably going to want to refer to the generators in some structure and not explicitly (if you decide you want n to be 10, you don't want to have to go around and add up to x_9 everywhere) so R.gens() and R.gens_dict() will come in handy:

sage: R.gens()
(x_0, x_1, x_2, x_3, x_4)
sage: R.gens_dict()
{'x_4': x_4, 'x_2': x_2, 'x_3': x_3, 'x_0': x_0, 'x_1': x_1}

more This post is a wiki. Anyone with karma >750 is welcome to improve it.

more