How do you create different variable names while in a loop?

Takkun picture Takkun · May 31, 2011 · Viewed 340.5k times · Source

For example purposes...

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

So I end up with string1, string2, string3... all equaling "Hello"

Answer

the wolf picture the wolf · May 31, 2011

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!