On Wed, Feb 22, 2012 at 10:24 AM, David Craig <dcdavem...@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
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to