0

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
Dataman
  • 3,457
  • 3
  • 19
  • 31
Toasterino
  • 55
  • 1
  • 11

2 Answers2

4

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]
n1c9
  • 2,662
  • 3
  • 32
  • 52
3

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.

Pythonista
  • 11,377
  • 2
  • 31
  • 50