Below is non-working and working code which generates a list of lists.
Example 1 does not work correctly, it repeats the last list appended over and over.
Example 2, where I replaced delete with creating a new list does work correctly.
# Example 1, this does not work correctly
l1 = []
l2 = []
x = 0
for n in range(0,3):
del l1[:] # deleting all list elements
for i in range(0,3):
l1.append(x)
x+=1
l2.append(l1)
print(l2)
# Example 2, this works correctly
l2 = []
x = 0
for n in range(0,3):
l1 = [] # creating the list each loop through
for i in range(0,3):
l1.append(x)
x+=1
l2.append(l1)
print(l2)
2 Answers 2
In your first example, l1 is the same list object the entire time. When you do l2.append(l1), you insert a reference to this l1 object into l2. When the loop restarts and you delete everything in l1, you also delete everything in the list inside l2, because that is the same list. You are appending the same list object to l2 multiple times, so every time you clear it, you clear every list in l2.
In the second example, you create a separate list object every time. Each list object is thus independent, and clearing one doesn't affect the others.
Comments
l2 and l1 refer to the same object (list). When you delete all the elements of the list, the change is reflected in l2 and l1.
Here, when the code executes l1 = [], l1's reference gets re-assigned. But l2's elements keep referring to the original object.