Creating a fallback list in python

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?

+5
source share
3 answers

A common idiom for this is y = x[:]. This makes a shallow copy xand saves it in 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().

+17
source

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

+4

AIX , :

y = list(x)

, . , , . - ( ).

, NOTHING y, , . :

y = tuple(x)

:

y = [a for a in x]

, ( ). , .

0

All Articles