1

I am having strange behavior with a list of lists in Python. There are two levels, but depending on how I set up the list, editing one of the levels either edits just the correct element, or all elements that share the 2nd reference.

This can be summarized as follows -- b and c are ititially the same (Python shows they are equivalent). Then I edit them the same way by changing the [1][1] entry, however for b, this impacts any entry with 2nd index=1 (ie adding to b[1][1] changes b[2][1]), where for c it only changes c[1][1]. This behavior is very puzzling, clearly something in the assignment of b relates the indexed entities to each other. Anyone know what is going on?

b = 10*[4*[0]]
c = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];

print(b==c);

b[1][1] += 2;
c[1][1] += 2;

print(b==c); 
Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80

0 Answers0