pretty basic: get variable name from list of strings?

Terry Reedy tjreedy at udel.edu
Mon Jul 29 19:17:42 EDT 2002


<chris> wrote in message
news:i1fbku0neslja6vup69542aojqaph1nem3 at 4ax.com...
> in the specific,
>
> if I have a list
>
> animals = ['horse_0', 'horse_1']
> horsenames = ['smokey', 'silver']
>
> how do assign variables with those strings as names?
>
> ie, I want
> horse_0 = "smokey"
> horse_1= "silver"
>
> but if I write animals[0] = "smokey", it replaces the value, it
> doesn't assign it.  What I want is like assign() or eval() in other
> languages.
>
> you can imagine i am trying to iterate over large indexes of
> animals[i] = 'horse_' + str(i)
> and then assign them from a value list
>
> or even screw the variable list and instead iterate over the
> value list
> 'horse_' + str(i) = horsenames[i].

I think you are looking for something like

g = globals() #
for i in range(len(horses)):
   g['horse_'+str(i)] = horses[i]

However, I strongly question whether you *really* want to do that.
Accessing a list of names such as horses thru an index is much easier
that thru a dict keyed with sequential strings.  Cluttering globals is
also a bad idea, and above will not work with locals().

Terry J. Reedy






More information about the Python-list mailing list