0

I'm doing some coding where it would be useful to reference variables named partially after another variable.

Something like this, but i in the variable name "variablei" changes to the value of i (variable0, variable1, etc.).

for i in range(0,10):
    print(variablei)

I tried thinking of ways this could be done in Python but variable[i] refers to the ith variable in, for example, the list called variable.

I know that this could be fixed using lists where instead of naming things like "variable1", "variable2" etc. you could just append a list called variable. But, I'm trying to reference many objects that have already been created by others.

Perhaps there's a way to list the variable names in the environment, search for a variable with a number concatenated on it, and then get the value of that variable? I'm sure there is, but perhaps there's an easier way?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    You shouldn't have similarly named variables; use a list or a dict. – chepner Mar 30 '23 at 19:06
  • Yeah, I thought so. I am using code by others that could have been written better. Thanks! – Lukas Taylor Mar 30 '23 at 19:08
  • 1
    "But, I'm trying to reference many objects that have already been created by others." Then you should change your design. Don't use dynamic variables, use *an appropriate data structure from the beginning* – juanpa.arrivillaga Mar 30 '23 at 19:15

0 Answers0