Variable names on the fly?

dsavitsk dsavitsk at e-coli.net
Thu Nov 14 14:57:12 EST 2002


"Gonçalo Rodrigues" <op73418 at mail.telepac.pt> wrote in message
news:r9u7tu8csfau7sjrpkbg85ttsjrphsec7t at 4ax.com...
> On Thu, 14 Nov 2002 19:13:22 -0000, "e-tones.co.uk"
> <admin at e-tones.co.uk> wrote:
>
> >Hi all, does python allow the creation of variable names on the fly, more
> >importantly lists.
> >
> >I have a stock list containing 5 elements, [0,0,0,0,0]
> >
> >Lets call it: list
>
> Don't - in your code that is. It will shadow the name of the list
> builtin and a sure way to make a mess out of your program.
>
> >
> >Now, via a loop, can I create list1, list2, list3 on the fly by
replicting
> >the original list, eg
> >
> >i = 1
> >for i in range(2)
> >    list+i = list
> >
> >Whats the proper format to concatenate (sp?) variable names. I used
list+i,
> >obviously this doesnt work, but what does :)
>
> As far as I know you cannot do this - but why would you? Why would you
> need such a weird thing? Just use a mapping dictionary
>
> <whatever name you what or more generally a hashable> -> value
>
> For example: calling our dictionary dct (not dict!) and your list lst
>
> for i in range(2):
>     dct['list' + str(i)] = lst

you could also do something like this (not that you should)

for i in range(2):
    exec('list' + str(i) + ' = lst')





More information about the Python-list mailing list