[Tutor] multiple list creation

Michael P. Reilly arcege@shore.net
Fri, 5 Jan 2001 15:35:36 -0500 (EST)


> I wonder how to create an empty list with a unique name for each item in a 
> sequence??
> 
>  >>>a=['one','two','three']
>  >>>for b in a:
>         b+'buffer'=[]

If you want to put these as global variables in a specific module,
say __main__, then you can use setattr to assigh a new variable.

>>> import __main__ # we may be in the __main__ module, but we need the
>>>                 # the reference to the module here; we could use the
...                 # name of any mdoule we wished here really
...
>>> a = [ 'one' ,'two', 'three' ]
>>> dir(__main__)
['__builtins__', '__doc__', '__main__', '__name__', 'a']
>>> for b in a:
...   setattr(__main__, '%sbuffer' % b, [])
...
>>> dir()
['__builtins__', '__doc__', '__main__', '__name__', 'a', 'b', 'onebuffer', 'threebuffer', 'twobuffer']
>>>

But more generally, try using the "exec" statement which takes a string
an executes it as a Python statement:

>>> a = [ 'one', 'two', 'three' ]
>>> dir()
['__builtins__', '__doc__', '__name__', 'a']
>>> for b in a:
...   exec '%sbuffer = []' % b
...
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'onebuffer', 'threebuffer', 'twobuffer']
>>>

The value of using exec instead of "import __main__; setattr(__main__,
...)" is that exec will create the variables in the proper current
namespace (local, global).  You cannot use eval() because the
assignment is a statement, eval works only with expressions.

Enjoy,
  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------