How to Actually Copy a List in Python
tl;dr: use the method. Say we have two Python lists – and . If we try to make a copy of and assign it to using the assignment operator , what really happens is that both and point to the same memory address. That means that any list-manipulating actions that are done on either or will affect the same list in memory. We don’t have actually have two separate lists we can act upon. In the example below, although we append the integer to , we can see that printing out shows the newly added element. That’s because both list variables point to the same memory address: Output of the program above: To make an actual copy, use the method. Then, when is modified, it is independent of , because is stored in a separate memory address. Now if we append the same integer to , will be completely unaffected. Output of the program above: Here’s more proof. We can print out the memory address of each variable to see when they’re the same and when they differ. We can do this using the function. Here are the same lists from above but this time with their unique identifiers printed out. In this case, the IDs match because both and point to the same memory address. The program above outputs: The memory addresses are the same. Now let’s try the same thing but using the method instead of just an assignment operation with : The program above outputs: We can see the memory addresses are different (most obvious due to the ending digits). Although I’ve been in the field for some time, I still have my smooth brain moments. This is a reminder to myself (and whoever reads this) to remember the basics! https://www.geeksforgeeks.org/python/python-list-copy-method/ https://www.geeksforgeeks.org/python/id-function-python/