1

I have the following python2 program:

A=[]
for i in range(2):
    A.append(list(["hello"])) 
print "A is",A

F=[]
for i in range(2):
    F.append(list(A))

print "F[0] is", F[0]
print "F[1] is", F[1]

F[0][0].append("goodbye")

print "F[0][0] is", F[0][0]
print "F[1][0] is", F[1][0]

When I run it, I get the output:

A is [['hello'], ['hello']]
F[0] is [['hello'], ['hello']]
F[1] is [['hello'], ['hello']]
F[0][0] is ['hello', 'goodbye']
F[1][0] is ['hello', 'goodbye']

I was expecting the contents of F[1][0] to be just ['hello']. I thought that the program's current behaviour would be normal if I had written F.append(A) instead of F.append(list(A)). But, by writing list(A) instead of just A I should be passing the list A by value, and not by reference.

What have I misunderstood here?


EDIT: The program has the same behaviour if I write F.append(A[:]) instead of F.append(list(A))

geo909
  • 394
  • 1
  • 6
  • 18

1 Answers1

1

list(a) and a[:] have limitations with collections of mutable objects, as inner object keep their references intact. You should use deepcopy in this case.

In particular, it should be F.append(copy.deepcopy(A)) instead of F.append(list(A)).

geo909
  • 394
  • 1
  • 6
  • 18
aldeb
  • 6,588
  • 5
  • 25
  • 48