Python creating variables with names from range

Question:

I want to use some code similar to what follows that actually works:

P = 20
n = 1
for x in range(1, P+1):
    Ax = n #Hoping that you can name the variable from the current element in the range
    n = n+1

I want to make varibles A1, A2, A3….A20 they would have the values 1, 2, 3…20 in this example…

Is this possible at all, and what coding does it require?

Cheers

Asked By: D Rayner

||

Answers:

You don’t actually want to do this. Instead, you want something like this:

P = 20
n = 1
A = []        # Or `A = list()`
for x in range(1, P+1):
    A.append(n)
    n += 1

Then, instead of A0, you do A[0] and instead of A5 you do A[5].

Here is the Python 3.x list documentation (I presume you are using Python 3.x due to using range rather than xrange.

Also, as I understand it, your code could just be this:

P = 20
A = []
for x in range(1, P+1):
    A.append(x)

Or this:

P = 20
A = [i for i in range(1, P+1)]

(See the documentation for list comprehensions, a very useful feature of Python.)

Or even:

P = 20
A = list(range(1, P+1))
Answered By: rlms

Do not try to dynamically name variables. That way madness lies.

Instead, leverage python’s data structures to do what you want. In most cases, people really want to be using a dict or a list.

a = {} 

for x in range(1,21):
    a[x] = x**2


b = []

for x in range(1,21):
    b.append(x**2)

You will get a feel for when you want to use one over the other. For example, in the above if I needed to quickly look up the square of a given integer, I would use a dict. If I instead just needed to do something to the collection of squares between 1 and 20, that’s when I use a list.

Trivial example, but this scales up as far as you need it to. Any hashable data type can be a key in a dictionary, so you’re no longer restricted from naming your variables with clunky letters and numbers – any object will do!

Answered By: roippi

I almost agree with all the answers and comments you got so far:
99.99% of the times, you don’t want to do this. It’s dangerous, ugly and bad.

However there is a way to do it, using exec:

P = 20
n = 1
for x in range(1, P+1):
    exec("A{} = n".format(x))
    n = n+1

Again, you probably shouldn’t use this.

Answered By: rahmu
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.