1

A pretty basic question...was wondering if there is a way to easily substitute part of a variable name with the looping index?

i.e.

value_1 = 1
value_2 = 2
value_3 = 3

for i in range (1,4):
    print value_i

Obviously the above code wouldn't work...but is it possible to substitute the number part of variable name with index i in Python?

Thank you.

333
  • 19
  • 2
  • You can definitely add those values to list and iterate the list. – Austin Jun 25 '20 at 04:21
  • Beside the point, but wouldn't recommend learning Python 2 at this point since it hit end-of-life in January. Python 3 is much better anyway. BTW welcome to SO! Check out the [tour], plus [ask] if you want advice. – wjandrea Jun 25 '20 at 04:23
  • 2
    Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) tl;dr use a list instead – wjandrea Jun 25 '20 at 04:24
  • 1
    It's worth taking the time to explore python's lists and dictionaries. Once you internalize those a bit, you won't want to do this. It is *really* the wrong way forward. – Mark Jun 25 '20 at 04:26
  • Thanks a lot for everyone's input. I did end up using a list. But it's nice to know the globals() function as well. – 333 Jun 28 '20 at 02:01

2 Answers2

1

Other than using a list, which is the obvious solution, you can also access variables using globals():

value_1 = 1
value_2 = 2
value_3 = 3

for i in range(1, 4):
    var_name = f"value_{i}"
    print(globals()[var_name])

The result would be:

1 
2 
3
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Roy2012
  • 11,755
  • 2
  • 22
  • 35
0
value_1 = 1
value_2 = 2
value_3 = 3

for i in range (1,4):
    print(globals()['value_%s' % i])

I would advise use of dictionaries or lists instead

Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22