2

I am confused with the following code

L1 = [3,6,9,12]
L2 = [L1]*3
L3=[list(L1)]*3
L4 = [list(L1) for i in range(3)]
L1[0]=100

 L2
[[100, 6, 9, 12], [100, 6, 9, 12], [100, 6, 9, 12]]

L3
[[3, 6, 9, 12], [3, 6, 9, 12], [3, 6, 9, 12]]

L4
[[3, 6, 9, 12], [3, 6, 9, 12], [3, 6, 9, 12]]

Why L3 and L4 not affected by the fifth line of code? It means that only L2 has shared object with L1. Can someone explain why L3 and L4 do not create shared object and only L2 does?

bner341
  • 525
  • 1
  • 7
  • 8

1 Answers1

0

list(foo) creates a new list object that copies the individual values of the items in foo. Thus modifying the foo object (in your case, L1) will not affect which values are in the new list.

L2 is a list which contains 3 references to L1.

L3 and L4 are lists which contain 3 copies of L1 each.

You can use the id() function to observe this.

Amber
  • 507,862
  • 82
  • 626
  • 550