I want to create a back-up list of another list in python. Here is an example of the code.
x = [1,2,3]
y = x
x.pop(0)
print y
This however yields the result y = [2,3]
when I want it to yield [1,2,3]
. How would I go about making the y list independent of the x list?
A common idiom for this is y = x[:]
. This makes a shallow copy of x
and stores it in y
.
Note that if x
contains references to objects, y
will also contain references to the same objects. This may or may not be what you want. If it isn't, take a look at copy.deepcopy()
.
Here is one way to do it:
import copy
x = [1,2,3]
y = copy.deepcopy(x)
x.pop(0)
print x
print y
from the docs here
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