[Tutor] regarding the list problem

Hugo Arts hugo.yoshi at gmail.com
Wed Feb 6 12:07:14 CET 2013


On Wed, Feb 6, 2013 at 9:48 AM, Kang, Yang Jae <kangyangjae at gmail.com>wrote:

This line:


> >>> a = [[0,0]]*3
>

creates a list, a, which contains the list object [0, 0] three times.
What's crucial to note is that it contains *the same object* three times,
not three different objects with the same value. You can verify this
yourself, with the id() function:

>>> a = [[0,0]] * 3
>>> a
[[0, 0], [0, 0], [0, 0]]
>>> id(a[0]), id(a[1]), id(a[2])
(41087144, 41087144, 41087144)
>>>

All three have the same id, therefore all three point to one and the same
object.

> >>> a****
>
> [[0, 0], [0, 0], [0, 0]]****
>
> >>> a[0][0] += 1****
>
> >>> a****
>
> [[1, 0], [1, 0], [1, 0]]
>
It should not be so strange, now, that if you modify a[0], this
modification will be reflected in a[1] and a[2] as well, since those are
all the same object.

Now, this can happen with lists, because they are mutable. If we do the
same with integers:

>>> a = [1] * 3
>>> a
[1, 1, 1]
>>> id(a[0]), id(a[1]), id(a[2])
(3779904, 3779904, 3779904)
>>> a[0] += 1
>>> a
[2, 1, 1]
>>>

You get the expected behaviour now, even though the list again contained
the same object three times. This is because integers are *immutable*,
meaning you cannot change them. So this line:

>>> a[0] += 1

did not modify the object, but created another integer object, with value
2, and assigned that to a[0]. The conclusion is that you should always be
mindful of whether your objects are mutable or not, and you should
understand what actually happens when you multiply a list by a constant, to
avoid these kinds of problems. In this case, what you wanted to do was
create three list objects with value [0, 0], not just the one. You may
either generate them with a loop or list comprehension, or simply write the
list out in its entirety:

>>> a = [[0,0] for i in range(3)]
>>> id(a[0]), id(a[1]), id(a[2])
(4070896, 41087984, 41061792)
>>> a = [[0, 0], [0, 0], [0, 0]]
>>> id(a[0]), id(a[1]), id(a[2])
(41087944, 41087824, 41069624)
>>>

This way, the lists are actually three different lists and not just the
same object three times (as you can see, they have different id's)

HTH,
Hugo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130206/d1843244/attachment.html>


More information about the Tutor mailing list