Creating a List of Empty Lists

Fuzzyman michael at foord.net
Thu Dec 4 15:49:11 CET 2003


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...) ?

Fuzzyman



http://www.Voidspace.org.uk 
The Place where headspace meets cyberspace. Online resource site -
covering science, technology, computing, cyberpunk, psychology,
spirituality, fiction and more.

---
http://www.atlantibots.org.uk
http://groups.yahoo.com/group/atlantis_talk/
Atlantibots - stomping across the worlds of Atlantis.
---
http://www.fuchsiashockz.co.uk   
http://groups.yahoo.com/group/void-shockz
---

Everyone has talent. What is rare is the courage to follow talent
 to the dark place where it leads. -Erica Jong
Ambition is a poor excuse for not having sense enough to be lazy.
         -Milan Kundera




More information about the Python-list mailing list