0

How can i create some variables with dynamic and static elements in one part together in python loop? Something like this:

Static part: self.var_li_. Dynamic part: da

for da in range(10):
   self.var_li_da = da

And my output would be:

var is : self.var_li_1 and value : 1
var is : self.var_li_2 and value : 2
var is : self.var_li_3 and value : 3
var is : self.var_li_4 and value : 4
...
A. Rodas
  • 20,171
  • 8
  • 62
  • 72
alireza
  • 1,173
  • 4
  • 19
  • 40

1 Answers1

1

Use setattr:

for da in range(10):
    setattr(self, 'var_li_{}'.format(da), da)
A. Rodas
  • 20,171
  • 8
  • 62
  • 72
  • Thx, solved!! i use setattr this way :for da in range(10): setattr(self, 'var_li_%s' %da, da) and not work, can i ask why ? – alireza Jun 08 '13 at 19:56
  • @alireza.m Glad it helped :) I prefer `format` instead of `%` for string interpolation, but both ways work for me in Python 3.3. – A. Rodas Jun 08 '13 at 20:06
  • thx, maybe i was wrong, i found this way too and it's work, but this way is right to use (because of exec)? http://stackoverflow.com/a/7422918/1170846 – alireza Jun 08 '13 at 20:14
  • 1
    @alireza.m The problem with `exec` is that you can execute arbitrary code, and that is something risky when you use string interpolation. Here it doesn't matter, but `setattr` is more natural in this context (setting an object attribute). – A. Rodas Jun 08 '13 at 20:20