I'm trying to create variable names, based on another variable in a loop. How would I go about doing something like this?
y = a changing integer
for x in range(0, y):
x += 1
var(x) = something[x]
print var1
print var2
I'm trying to create variable names, based on another variable in a loop. How would I go about doing something like this?
y = a changing integer
for x in range(0, y):
x += 1
var(x) = something[x]
print var1
print var2
I remember having this very same question when I first started learning Python. The short answer is that you shouldn't do it because it's a bad idea. It clogs up namespaces, makes code harder to debug, and much harder for people to read. Use a dictionary instead:
y = a changing integer
x = 0
var = {}
for x in range(0, y):
x += 1
var[x] = something[x]
You can use globals
as one way to dynamically create variables
e.g. for globals -
>>> for i in range(10):
... globals()['number_%d' % i] = i
>>> print(globals())
>>> {'__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'number_3': 3,
'number_9': 9, 'number_1': 1, 'number_7': 7, 'number_4': 4, 'number_6': 6,
'number_0': 0, '__doc__': None, '__package__': None, 'number_8': 8, 'number_5': 5,
'__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', 'i': 9,
'__spec__': None, 'number_2': 2}
You could use your condition to specify how these are assigned.
But for what you need this sounds and usually always is unnecessary. A tuple
, list
even a dict
as suggested in the other answer would be better.