Srijan
Srijan

Reputation: 1284

Naming a variable on the basis of index in loop

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.

Upvotes: 1

Views: 3236

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

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'

Upvotes: 7

Related Questions