[Tutor] Create a table by writing to a text file.

Jerry Hill malaclypse2 at gmail.com
Wed Feb 22 16:41:35 CET 2012


On Wed, Feb 22, 2012 at 10:24 AM, David Craig <dcdavemail at gmail.com> wrote:

> you had me worried for a minute, but
> a = [[]] * 3
> a[0]=[1,2,3]
> a
> [[1, 2, 3], [], []]
>

That's not the same thing.  In your example you create three copies of the
same empty list inside your outer list.  You then throw away the first copy
of the empty list and replace it with a new list.  What Peter showed was
mutating that inner list in place.  If you aren't really, really careful,
you will eventually get bitten by this if you create your lists with
multiplication.

>>> container = [[]] * 3

You can see that this really is three references to the exact same list:
>>> print [id(item) for item in container]
[17246328, 17246328, 17246328]

If you replace the items, you're fine:
>>> container[0] = [1, 2, 3]
>>> print [id(item) for item in container]
[17245808, 17246328, 17246328]

But as soon as you change the contents of one of those duplicate lists,
you're in trouble:
>>> container[1].append('Data')
>>> print container
[[1, 2, 3], ['Data'], ['Data']]
>>> print [id(item) for item in container]
[17245808, 17246328, 17246328]
>>>

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120222/6d157f63/attachment.html>


More information about the Tutor mailing list