eval ?

Chris feb04.20.netman at spamgourmet.com
Fri Feb 20 09:28:37 EST 2004


One way to do this is:

for index in range(1,4):
    list=[]
    for index in range(1,7):
    if <condition>:
        list.append(1)
        locals()['list_'+str(index)] = list

Of course this isn't going to work the way you expect, because you're
assigning a pointer to "list" to "list_n" with each iteration, and at the
end, all of your "list_n" variables are going to reference the same object,
the one orginally referenced by "list"

Perhaps you are looking for something like:

>>> dict([('list_'+str(n), [1,]*n) for n in xrange(1,7) if <condition>])

so if condition is "n in (2,4,6)", you'd get output like:

>>> foo = dict([('list_'+str(n), [1]*n) for n in xrange(1,7) if n in
(2,4,6)])
>>> foo
{'list_2': [1, 1], 'list_6': [1, 1, 1, 1, 1, 1], 'list_4': [1, 1, 1, 1]}
>>> foo['list_4']
[1, 1, 1, 1]

Note that I'm createing a brand new list (via "[1]*n") with each iteration
of the list comprehension, rather than using a reference to a previously
created list.

HTH
Chris

"Angelo Secchi" <secchi at sssup.it> wrote in message
news:mailman.104.1077277571.27104.python-list at python.org...
>
> I'm trying to use eval (is the right function? ) to generate empty lists
> with different names(es. list_1, list_2, list_3, ...) in a loop similar
> to:
>
> for index in range(1,4):
> list=[]
> for index in range(1,7):
> if <condition>:
> list.append(1)
> foo='list_'+str(index)+'=list'
> eval(foo)
>
> I am not a programmer as you probably see from the code and I do not
> even know if this is the right approach to do that in Python (I used
> this structure with Matlab that I want now to dismiss ...)
>
> Any help?
> Thanks
> angelo
>





More information about the Python-list mailing list