[Tutor] create and fill a list with exec?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 9 Feb 2001 23:36:05 -0800 (PST)


On Fri, 9 Feb 2001 michaelbaker@operamail.com wrote:

> how can I create an empty list and then fill it with stuff at the time of 
> creation or without calling it explicitly by name later?
>  >>> dir()
> ['__builtins__', '__doc__', '__name__']
>  >>> a=[1,2,3,4,5]
>  >>> for b in a:
> 	exec 'buffer%s=[]' %b

As a note, if you're beginning to learn the language, I'd recommend
against using exec() --- there's probably an easier way to do what you're
doing.

It looks like you're making several lists (buffer1, buffer2, buffer3,
buffer4, and buffer5).  It might be better to make a list of those buffers
instead:

###
>>> mybuffers = []
>>> for i in range(5):
...     mybuffers.append([])
... 
>>> mybuffers
[[], [], [], [], []]
###

Now we can treat buffer1 as mybuffers[0], buffer2 as mybuffers[1], etc.  
This is nice because we can now pass off all the buffers with a single
name, "mybuffers".

Lists are really nice, and using them will allow you to avoid tricky
exec() stuff.  Alan Gauld explains them pretty nicely in his tutorial
here:

    http://www.crosswinds.net/~agauld/

Good luck!