Fix Python – How do you create different variable names while in a loop? [duplicate]

Question

Asked By – Takkun

For example purposes…

for x in range(0,9):
    string'x' = "Hello"

So I end up with string1, string2, string3… all equaling “Hello”

Now we will see solution for issue: How do you create different variable names while in a loop? [duplicate]


Answer

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!

This question is answered By – the wolf

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0