-1

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

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Visualization of #1 code

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.

Visualization of #2 code

Here, when the code executes l1 = [], l1's reference gets re-assigned. But l2's elements keep referring to the original object.

2 Comments

This is incredibly useful. Thank you.
@jbiondo - Welcome. You should upvote an answer that you find useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.