[ python-Bugs-1722956 ] x = [[]]*2; x[0].append doesn't work

SourceForge.net noreply at sourceforge.net
Mon May 21 22:03:46 CEST 2007


Bugs item #1722956, was opened at 2007-05-21 19:21
Message generated for change (Comment added) made by gbrandl
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1722956&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Parser/Compiler
Group: None
>Status: Closed
>Resolution: Invalid
Priority: 5
Private: No
Submitted By: Jeff Britton (metal_one)
Assigned to: Nobody/Anonymous (nobody)
Summary: x = [[]]*2;  x[0].append doesn't work

Initial Comment:
This bug is hard to explain in words.  It is easiest to just look at the Interactive Python commands issued below.

<x> is assigned a list of two empty lists, however there is something wrong with <x>.
<y> is assigned a list of two empty lists using list comprehension.  <y> is ok.
A check of x == y, shows them equal.
However, when trying to append [1,2] to x[0] both x[0] and x[1] are appended to. 
The same operation on <y> works correctly.


>>> x = [[]]*2
>>> y = [[] for i in range(2)]
>>> x == y
True
>>> x[0].append([1,2])
>>> x
[[[1, 2]], [[1, 2]]]
>>> y[0].append([1,2])
>>> y
[[[1, 2]], []]


I have tested with Python 2.5 and 2.4.

----------------------------------------------------------------------

>Comment By: Georg Brandl (gbrandl)
Date: 2007-05-21 20:03

Message:
Logged In: YES 
user_id=849994
Originator: NO

This is not a bug. "x" is a list containing two references to the same
list object, while "y" is a list containing references to two distinct list
objects.

The "==" operator doesn't test for identity, but compares list contents,
which is why it yields True above.

(Please ask any further questions about this behavior on the python-list
mailing list.)

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1722956&group_id=5470


More information about the Python-bugs-list mailing list