3

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

Eric
  • 41
  • 1
  • 4

2 Answers2

2

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]
Darkcyan
  • 21
  • 1
1

You can, in this case, use:

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

Output for x and y:

[1.0, 2.0, 3.0, 4.0]
[9.0, 2.0, 3.0, 4.0]

But read this.

Community
  • 1
  • 1
Spherical Cowboy
  • 565
  • 6
  • 14