Creating a List of Empty Lists

Erik Max Francis max at alcyone.com
Thu Dec 4 16:44:12 EST 2003


Samuel Tardieu wrote:

> You can use one of the three (there are more)
> 
>   ([[]]*n)[:]

This won't work.  [:] makes a shallow copy.  This will make a different
containing list, but the contained lists will still be identical:

>>> s = [[]]*10
>>> s = [[]]*5 
>>> t = s[:]
>>> id(s)
1076779980
>>> id(t)
1076780300
>>> map(lambda (x, y): x is y, zip(s, t))
[True, True, True, True, True]
>>> s[0].append(2)
>>> s
[[2], [2], [2], [2], [2]]
>>> t
[[2], [2], [2], [2], [2]]

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ 
\__/ I'm sharing the joy / I'm glowing like sunshine
    -- Chante Moore




More information about the Python-list mailing list