creating lists question?

Mel Wilson mwilson at the-wire.com
Wed Mar 24 07:41:54 EST 2004


In article <c3qu0d$rfl$1 at news.service.uci.edu>,
Josiah Carlson <jcarlson at nospam.uci.edu> wrote:
>> I'm not sure this is doing what I want it to do. In the example I gave I
>> want a new list call "aaa" another list called "bbb"... so I can append to
>> the new list  i.e., bbb.append().  It may be that your example does this but
>> it appears to be (with my limited knowledge) that it's creating a list of
>> lists, when all I want is a new isolated list.
>
>Matt already gave an answer for how to do it using exec.  There is
>another method:
>
>for name in list1:
>     locals()[name] = []
>
>The above gets the dictionary for the local namespace, and makes the
>name given point to a new list.
>
>This doesn't have the same security holes as exec, but may have
>(non-exploitable) security holes, eg lists with builtin or module names.

Modifying locals() is not entirely like creating a variable:

Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f (x):
...     print locals()
...     locals()['b'] = x
...     print locals()
...     if x == 'x':
...         print b
...     print
...
>>> f('y')
{'x': 'y'}
{'x': 'y', 'b': 'y'}

>>> f('x')
{'x': 'x'}
{'x': 'x', 'b': 'x'}
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in f
NameError: global name 'b' is not defined


        Regards.        Mel.



More information about the Python-list mailing list