programmatically define a new variable on the fly

Bart Ogryczak B.Ogryczak at gmail.com
Fri Aug 10 07:08:31 EDT 2007


On 10 ago, 00:11, Lee Sander <lesa... at gmail.com> wrote:
> Hi,
>
> I would like to define a new variable which is not predefined by me.
> For example,
> I want to create an array called "X%s" where "%s" is to be determined
> based on the data I am processing. So, for example, if I the file
> I'm reading has
> g 99
> on the first line, I want to create a new variable  called "Xg" whose
> length
> is 99.
> I tried eval("Xg=[0]*99") but that did not work.

>>> letter = 'g'
>>> import __main__
>>> setattr(__main__,'X%s'%letter,[0]*99)
>>> Xg
[0, 0, 0 ...

Anyway, I don´t see the point in this. Why don´t you just use
something like X['g'] instead?




More information about the Python-list mailing list