Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a back-up list in python

Tags:

python

list

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?

like image 209
Michael Avatar asked May 23 '11 17:05

Michael


2 Answers

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().

like image 128
NPE Avatar answered Oct 02 '22 00:10

NPE


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

like image 42
Michael Easter Avatar answered Oct 02 '22 02:10

Michael Easter