I want to back up another list in python. Here is a sample code.
x = [1,2,3] y = x x.pop(0) print y
This, however, gives the result y = [2,3]when I want it to give [1,2,3]. How can I make list y independent of list x?
y = [2,3]
[1,2,3]
A common idiom for this is y = x[:]. This makes a shallow copy xand saves it in y.
y = x[:]
x
y
Please note that if it xcontains links to objects, yit will also contain links to the same objects. This may or may not be what you want. If not, take a look copy.deepcopy().
copy.deepcopy()
Here is one way to do this:
import copy x = [1,2,3] y = copy.deepcopy(x) x.pop(0) print x print y
docs here
AIX , :
y = list(x)
, . , , . - ( ).
, NOTHING y, , . :
y = tuple(x)
:
y = [a for a in x]
, ( ). , .