I am trying to create variable for each iteration of the for loop:
for i in range(10):
x(i) = 'abc'
so that I would get x1, x2, x3, x4, .... x10, all equal to 'abc'
Anyone know how to do it? Thanks!
I am trying to create variable for each iteration of the for loop:
for i in range(10):
x(i) = 'abc'
so that I would get x1, x2, x3, x4, .... x10, all equal to 'abc'
Anyone know how to do it? Thanks!
You should not be doing that, store your values in a dict
if you want to access them by name, or a list
if you want to access them by index, but if you really insist:
for i in range(10):
locals()["x" + str(i)] = "abc" # use globals() to store the vars in the global stack
print(x3) # abc
This is probably the easiest way for beginners. You might want to learn how to use lists:
>>> x = []
>>> for i in range(10):
x.append('abc')
>>> print(x[0])
abc
>>> print(x[8])
abc
>>> print(x)
['abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc']
You can also use globals or locals:
>>> for i in range(10):
globals()["x" + str(i)] = 'abc'
>>> x1
'abc'
Useful links: