Is this a bug in Python or something I do not understand.

D

davidalvi

Consider these two lists comprehensions:

L1=[[1 for j in range(3)] for i in range(3)]
L2=[[1]*3]*3

print L1
print L2
print L1==L2

The result is:

[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
True

So far, everything is OK, but let us now modify the lists' contents in
the following way:

for i in range(3):
for j in range(3):
if j<i:
L1[j]=0
L2[j]=0
print L1
print L2
print L1==L2

The output is now:

[[1, 1, 1], [0, 1, 1], [0, 0, 1]]
[[0, 0, 1], [0, 0, 1], [0, 0, 1]]
False

It seems a misbehaviour in Python, or there is something I do not
understand in the syntax ????
 
M

Miles

Consider these two lists comprehensions:

L1=[[1 for j in range(3)] for i in range(3)]
L2=[[1]*3]*3
[snip]

It seems a misbehaviour in Python, or there is something I do not
understand in the syntax ????

It's not a Python bug. Does this help illuminate the difference?
L1 = [object() for j in range(3)]
L2 = [object()] * 3
[id(o) for o in L1] [164968, 164976, 164984]
L1[0] is L1[1] False
[id(o) for o in L2] [164992, 164992, 164992]
L2[0] is L2[1]
True

-Miles
 
C

Chris Rebert

Consider these two lists comprehensions:

L1=[[1 for j in range(3)] for i in range(3)]
L2=[[1]*3]*3
So far, everything is OK, but let us now modify the lists' contents in
the following way:
It seems a misbehaviour in Python, or there is something I do not
understand in the syntax ????

The latter, and it's a FAQ. Please read
http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list
(it's question 4.6).

Cheers,
Chris
 
C

Casey

L1 is a list of three different lists, although each list holds the
same values.

L2 is a list of three references to the same list (the '*' operator
doesn't do a deep copy). So when you modify any of the referenced
lists, you modify all of them.

Try this:
q = [1, 1, 1]
r = [q, q, q]
r [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
r[0][0] = 999
r
[[999, 1, 1], [999, 1, 1], [999, 1, 1]]

Regards, Casey
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,219
Latest member
KristieKoh

Latest Threads

Top