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.

4
  • 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 ? Commented Jun 24, 2013 at 9:02
  • 3
    You don't want to do this, /thread Commented Jun 24, 2013 at 9: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. Commented Jun 24, 2013 at 9:15
  • 1
    I'm still curious about your motivation. Commented Jun 24, 2013 at 10:41

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.