How do you create different variable names while in a loop? [duplicate]
Solution 1:
Sure you can; it's called a dictionary:
d = {}
for x in range(1, 10):
d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
'string2': 'Hello',
'string3': 'Hello',
'string4': 'Hello',
'string5': 'Hello',
'string6': 'Hello',
'string7': 'Hello',
'string8': 'Hello',
'string9': 'Hello'}
I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!
Solution 2:
It is really bad idea, but...
for x in range(0, 9):
globals()['string%s' % x] = 'Hello'
and then for example:
print(string3)
will give you:
Hello
However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to know how to do it, but did not want to use it.
Solution 3:
One way you can do this is with exec()
. For example:
for k in range(5):
exec(f'cat_{k} = k*2')
>>> print(cat_0)
0
>>> print(cat_1)
2
>>> print(cat_2)
4
>>> print(cat_3)
6
>>> print(cat_4)
8
Here I am taking advantage of the handy f string formatting in Python 3.6+