programmatically define a new variable on the fly

Dustan DustanGroups at
Fri Aug 10 00:30:08 CEST 2007

On Aug 9, 5:11 pm, Lee Sander <lesa... at> 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.

eval only evaluates expressions. To go about the problem that way, you
would use exec, not eval.

Of course, use of exec generally means you're going about the problem
the wrong way; it looks to me like a better way to do what you're
doing is to create a dictionary to hold your values. So, given the
variables data (the dictionary), name (in your example, 'g') and
*size* (in your example, 99), you can add it  data as shown:

data[name] = [0]
data[name] *= size

Note that by splitting the '[0]*size' code into two lines as shown
above, you don't create an intermediate list object that gets thrown
away right after creation.

More information about the Python-list mailing list