Assigning values to variables in a list using a loop

You can access the dictionary of global variables with the globals() built-in function. The dictionary uses strings for keys, which means, you can create variables with names given as strings at run-time, like this:

>>> var_names = ["one", "two", "three"]
>>> count = 1
>>> for name in var_names:
...  globals()[name] = count
...  count += 1
... 
>>> one
1
>>> two
2
>>> three
3
>>> globals()[raw_input()] = 42
answer
>>> answer
42

Recommended reading

Leave a Comment