Using a loop in Python to name variables [duplicate]

Use a dictionary instead. E.g:

doubles = dict()

for x in range(1, 13):
    doubles[x] = x * 2

Or if you absolutely must do this AND ONLY IF YOU FULLY UNDERSTAND WHAT YOU ARE DOING, you can assign to locals() as to a dictionary:

>>> for x in range(1, 13):
...     locals()['double_{0}'.format(x)] = x * 2
... 
>>> double_3
6

There never, ever should be a reason to do this, though – since you should be using the dictionary instead!

Leave a Comment