Search code examples
python-3.xlistreferencegarbage-collection

Python List Copying Garbage Collection


I have a list a and set it to [1, 2, 3, 4, 5]. Then I set b to a. My goal is to make two seperate versions of a, aka, I want b to change while a dosen't change. However, when I remove 5 from b, a becomes, [1, 2, 3, 4], exactly the same as b! My code is shown below:

a = [1, 2, 3, 4, 5]
b = a
b.remove(5)
print(b, a)

Here is my output:

[1, 2, 3, 4] [1, 2, 3, 4]

How can I achieve my goal?


Solution

  • To make a copy of a, you can use:

    b = a[:]
    

    This question has been asked already.