1

I want to implement a loop where in each iteration I name the variable according to iterator value. For instance-

for i in range(1,10):
    r<value of i> = # some value

Is there a way i can do it, other than making all these variables as string keys in a dictionary as mentioned in How do you create different variable names while in a loop? (Python). I want each to be a separate variable.

Community
  • 1
  • 1
Srijan
  • 1,234
  • 1
  • 13
  • 26
  • 2
    You should detail what you want to do exactly. I think you have some misunderstanding of what a variable purpose is. Did you consider loading your values into a List ? – AsTeR Jun 24 '13 at 09:02
  • 3
    You don't want to do this, /thread – jamylak Jun 24 '13 at 09:03
  • @AsTeR Yes, I understand what a variable is and I consider using list is a good option here. But using separate variables is required by the problem I am trying to solve. The answer given serves my purpose. Thanks for your time. – Srijan Jun 24 '13 at 09:15
  • 1
    I'm still curious about your motivation. – AsTeR Jun 24 '13 at 10:41

1 Answers1

7

You can do that using globals(), but it's a bad idea:

>>> for i in range(1,10):
...         globals()['r'+str(i)] = "foo"
...     
>>> r1
'foo'
>>> r2
'foo'

Prefer a dict over globals():

>>> my_vars = dict()
>>> for i in range(1,10):
        my_vars['r'+str(i)] = "foo"
>>> my_vars['r1']
'foo'
>>> my_vars['r2']
'foo'
Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504