Skip to content Skip to sidebar Skip to footer

How To Rename Variables In A Loop In Python

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

Solution 1:

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.

Solution 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.

Solution 3:

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]

Solution 4:

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

Post a Comment for "How To Rename Variables In A Loop In Python"