How can i call the continuous variables automatically in python

Viewed 269

I made automatically named variables by looping them - using for-loop - , like below

for i in range(10):
  global()['variables_{}'.format(i)]=i

there is "s" at the end of global but this site doesn't allow it.

i can't get value of variables when i try to call it automatically by using for loop like below

for i in range(10):
  print('variables_{}'.format(i))

code above outcome is not a 0,1,2,3... but variables_0,variables_1, variables_2 ... i want to get 0,1,2,3 (the value of variables_i)

2 Answers

You need to use eval() function. It converts string to corresponding variable/statement. Your code should look like this:

 for i in range(10):
   print(eval('variables_{}'.format(i)))

Please let me know if I couldn't help you

But anyway, if your case isn't educational or very specific, it is better to use list.

You can use globals().get('var') or globals()['var']

for i in range(10):
  print(globals().get('variables_{}'.format(i)))

output 1,2,3 etc.

But I don't suggest using globals. What I do recommend, is using a dictionary where the keys are your variable names and the values are the value of the variable.

#create the dictionary which looks like:
#{'variables_0': 0, 'variables_1': 1, 'variables_2': 2, 'variables_3': 3, 'variables_4': 4, 'variables_5': 5, 'variables_6': 6, 'variables_7': 7, 'variables_8': 8, 'variables_9': 9}
vars = {}
for i in range(10):
    vars['variables_{}'.format(i)]=i

#we can access a single variables value like as shown below
#or use `.get('variables_1')`, 
#so that if a variable is not present in the dictionary, an error #is not thrown and instead we get (None)

print(vars['variables_1'])

#or we can loop through our dictionary printing each variables value
for v in vars.values():
    print(v)
Related