You can use exec for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
Answer from Jack Leow on Stack OverflowIf you really want to create them on the fly you can assign to the dict that is returned by either globals() or locals() depending on what namespace you want to create them in:
globals()['somevar'] = 'someval'
print somevar # prints 'someval'
But I wouldn't recommend doing that. In general, avoid global variables. Using locals() often just obscures what you are really doing. Instead, create your own dict and assign to it.
mydict = {}
mydict['somevar'] = 'someval'
print mydict['somevar']
Learn the python zen; run this and grok it well:
>>> import this
Though I don't see much point, here it is:
for i in xrange(0, len(prices)):
exec("price%d = %s" % (i + 1, repr(prices[i])));
Videos
Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.
a = {}
k = 0
while k < 10:
# dynamically create key
key = ...
# calculate value
value = ...
a[key] = value
k += 1
There are also some interesting data structures in the collections module that might be applicable.
globals() returns a dictionary of the module's variables. You can create a new variable by creating a key on that dictionary:
# By default, a module has some hidden variables defined
print({k: v for k, v in globals().items() if not k.startswith("__")})
for i in range(1, 11):
globals()[f"my_variable_{i}"] = i
print()
print(my_variable_1)
print(my_variable_2)
# and so on
print()
print({k: v for k, v in globals().items() if not k.startswith("__")})
Result:
{}
1
2
{'i': 10, 'my_variable_1': 1, 'my_variable_2': 2, 'my_variable_3': 3, 'my_variable_4': 4, 'my_variable_5': 5, 'my_variable_6': 6, 'my_variable_7': 7, 'my_variable_8': 8, 'my_variable_9': 9, 'my_variable_10': 10}