Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename variables in a loop in Python [duplicate]

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

like image 232
ajor Avatar asked Mar 24 '23 07:03

ajor


2 Answers

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.

like image 134
MartinStettner Avatar answered Apr 02 '23 17:04

MartinStettner


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]
like image 36
StarlitGhost Avatar answered Apr 02 '23 15:04

StarlitGhost