6

I want to run a program in Python which loops several times, creating a NEW array each time - i.e. no data is overwritten - with the array named with a reference to the loop number, so that I can call it in subsequent loops. For instance, I might want to create arrays x0, x1, x2, ..., xi in a loop running from 0 to i, and then call each of these in another loop running over the same variables. (Essentially the equivalent of being able to put a variable into a string as 'string %d %(x)').

2
  • 15
    The best way is not to do this... use a list (or dictionary) instead Commented Apr 17, 2013 at 10:30
  • 3
    Your problem is that you are using local variables where you should be using a list or dictionary instead. Commented Apr 17, 2013 at 10:32

4 Answers 4

8

You can access the globals() dictionary to introduce new variables. Like:

for i in range(0,5):
    globals()['x'+str(i)] = i

After this loop you get

>>> x0, x1, x2, x3, x4
(0, 1, 2, 3, 4)

Note, that according to the documentation, you should not use the locals() dictionary, as changes to this one may not affect the values used by the interpreter.

Sign up to request clarification or add additional context in comments.

5 Comments

Except that it doesn't work for locals()
Yes, I already changed my answer. Although it seems to work, if you only introduce new variables (and don't change their value afterwards)
Note to anyone reading this answer : PLEASE DONT DO SUCH A STUPID THING. The correct solution is to use a dict or list.
I didn't suggest that this is a good way to do anything. But I believe it is a correct answer to a perfectly valid original question. Perhaps you might want to reread the SO section on downvoting ...
@brunodesthuilliers There are a couple of scenarios where it might make sense to modify the global environment (there might be a reason for the presence of the globals() dict after all...) Without knowing anything more, you cannot say, if this is the case here.
2

Using a dict:

arraysDict = {}
for i in range(0,3):
    arraysDict['x{0}'.format(i)] = [1,2,3]

print arraysDict
# {'x2': [1, 2, 3], 'x0': [1, 2, 3], 'x1': [1, 2, 3]}
print arraysDict['x1']
# [1,2,3]

Using a list:

arraysList = []
for i in range(0,3):
    arraysList.append([1,2,3])

print arraysList
# [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
print arraysList[1]
# [1, 2, 3]

Comments

2

Relying on variables's names and changing them is not the best way to go.

As people already pointed out in comments, it would be better to use a dict or a list instead.

Comments

0

You can create an object for this, and then use the setattr function for this. Basically, it will work like this:

setattr(myobject, 'string', value)

It is the same as doing : myobject.string = value

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.