How do I copy the contents of a list and not just a reference to the list in Python?
Look at the copy module, and notice the difference between shallow and deep copies:
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
Use a slice notation.
newlist = oldlist
This will assign a second name to the same list
newlist = oldlist[:]
This will duplicate each element of oldlist into a complete new list called newlist
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With