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
While aix has the most parsimonious answer here, for completeness you can also do this:
y = list(x)
This will force the creation of a new list, and makes it pretty clear what you're trying to do. I would probably do it that way myself. But be aware- it doesn't make a deep copy (so all the elements are the same references).
If you want to make sure NOTHING happens to y, you can make it a tuple- which will prevent deletion and addition of elements. If you want to do that:
y = tuple(x)
As a final alternative you can do this:
y = [a for a in x]
That's the list comprehension approach to copying (and great for doing basic transforms or filtering). So really, you have a lot of options.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.