List problem

Mel mwilson at the-wire.com
Sun Dec 16 19:10:22 EST 2007


Alan Bromborsky wrote:
> I wish to create a list of empty lists and then put something in one of 
> the empty lists.  Below is what I tried, but instead of appending 1 to 
> a[2] it was appended to all the sub-lists in a.  What am I doing wrong?
> 
> a = 6*[[]]
>  >>> a
> [[], [], [], [], [], []]
>  >>> a[2].append(1)
>  >>> a
> [[1], [1], [1], [1], [1], [1]]
>  >>> 

What you've done is equivalent to

x = []
a = [x, x, x, x, x, x]
del x

An idiom for what you want is

a = [[] for y in xrange (6)]

which will populate a with 6 distinct empty lists.

	Cheers,		Mel.



More information about the Python-list mailing list