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
  • 14,704
  • 9
  • 39
  • 61
hyades
  • 2,920
  • 1
  • 15
  • 33
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
  • 15,266
  • 5
  • 29
  • 41
  • 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
  • 316
  • 1
  • 3