Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Make Copy of List [duplicate]

How do I make a copy of a list, so I can edit the copy without affecting the original. Ex:

x = [1., 2., 3., 4.]
y = x
y[0] = 9.

The output is:

x: [9.0, 2.0, 3.0, 4.0] 
y: [9.0, 2.0, 3.0, 4.0] 

when I want x to be:

x: [1.0, 2.0, 3.0, 4.0]

So how do I make a copy of a variable while keeping the original unchanged?

Thanks in advance,

Eric

like image 210
Eric Avatar asked May 26 '26 04:05

Eric


1 Answers

Just wrap x with python's list function when declaring y and it works!

x = [1, 2, 3, 4]
y = list(x)
y[0] = 9

print x
print y

#This prints the following
#[1, 2, 3, 4]
#[9, 2, 3, 4]
like image 57
Darkcyan Avatar answered May 28 '26 18:05

Darkcyan