Creating a List of Empty Lists

Anton Vredegoor anton at vredegoor.doge.nl
Thu Dec 4 11:45:16 EST 2003


michael at foord.net (Fuzzyman) wrote:

>Pythons internal 'pointers' system is certainly causing me a few
>headaches..... When I want to copy the contents of a variable I find
>it impossible to know whether I've copied the contents *or* just
>created a new pointer to the original value....
>
>For example I wanted to initialize a list of empty lists....
>
>a=[ [], [], [], [], [] ] 
>
>I thought there has to be a *really* easy way of doing it - after a
>bit of hacking I discovered that :
>a = [[]]*10 appeared to work
>
>however - using it in my program called bizarre crashes....
>I eventually discovered that (as a silly example) :
>a = [[]]*10
>b=-1 
>while b < 10:
>    b += 1
>    a[b] = b
>print a 
>
>Produced :
>[ [9], [9], [9]......
>
>Which isn't at all what I intended...............
>What is the correct, quick way of doing this (without using a loop and
>appending...) ?

Here it produced an IndexError. After changing "b < 10" into "b < 9"
the code produced:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

I see some other posters already gave you the answer. I'll do
something different and give you the question :-)

n = 4
agents = [[]]*n
print agents 
agents[0].append('Smith')
print agents 
neos = map(list,[[]]*n)
print neos 
neos[0].append('Neo')
print neos

output is:

[[], [], [], []]
[['Smith'], ['Smith'], ['Smith'], ['Smith']]
[[], [], [], []]
[['Neo'], [], [], []]

The question is:

Why is "Smith" copied to all elements in the matrix? 

(or is that another movie :-)

Anton







More information about the Python-list mailing list