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)').

Maroun
  • 94,125
  • 30
  • 188
  • 241
ajor
  • 1,592
  • 7
  • 22
  • 40

4 Answers4

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.

MartinStettner
  • 28,719
  • 15
  • 79
  • 106
  • 1
    Except that it doesn't work for `locals()` – John La Rooy Apr 17 '13 at 10:36
  • Yes, I already changed my answer. Although it seems to work, if you only introduce new variables (and don't change their value afterwards) – MartinStettner Apr 17 '13 at 10:38
  • 3
    Note to anyone reading this answer : PLEASE DONT DO SUCH A STUPID THING. The correct solution is to use a dict or list. – bruno desthuilliers Apr 17 '13 at 10:50
  • 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 ... – MartinStettner Apr 17 '13 at 10:55
  • 1
    @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. – MartinStettner Apr 17 '13 at 11:03
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.

glglgl
  • 89,107
  • 13
  • 149
  • 217
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]
StarlitGhost
  • 420
  • 4
  • 13
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

Paco
  • 4,520
  • 3
  • 29
  • 53