0

I have a lot of identical variables that differ only with the last character

b1 = Class(argument)
b2 = Class(argument)
b3 = Class(argument)
b4 = Class(argument)
b5 = Class(argument)
b6 = Class(argument)

Is there a way to create them in a loop or somehow?

messier101
  • 101
  • 7
  • 1
    Possible duplicate of http://stackoverflow.com/questions/8799446/is-it-possible-to-dynamically-create-local-variables-in-python – twasbrillig Dec 26 '14 at 08:53

3 Answers3

3

You can use a dictionary for this purpose

d = {}
for i in range(1, 7):
    d['b' + str(i)] = Class(argument)
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
hyades
  • 3,110
  • 1
  • 17
  • 36
2
for i in xrange(1,7):exec("b%d=Class(argument)" % i)

Then you can check with:

from pprint import pprint
pprint(locals())
atupal
  • 16,404
  • 5
  • 31
  • 42
  • So I made this: `for i in range(1,7):exec("b%d=Class(argument)" % i)` - changed xrange() to range(). Thanks! – messier101 Dec 26 '14 at 08:10
2

You could also use a list

b = []
for i in range(1,7):
    b.append(Class(argument))

or

b = [Class() for x in range(1,7)]
baited
  • 326
  • 1
  • 3