0

I have a problem regarding the nature of the nested list. When I tried to change the variable assigned to it, it was also changed. Why does this happen? I would appreciate any help finding a way around this.

x = list();
y= [1,2,3,4] 
x.append(y)
print x   #return [[1,2,3,4]]
del y[-1]
print x   #return [[1,2,3]
vekerdyb
  • 1,213
  • 12
  • 26
Dave N.
  • 138
  • 1
  • 8

2 Answers2

0

newlist.append(list(oldlist)) should do the trick as well.

0

When I tried to change the variable assigned to it, it was also changed.

You're not changing variables there. del y[-1] does nothing to the variable y, it does something to the object (list) denoted by y. (As opposed to del y, which really does delete the variable y.)

Why does this happen?

Because y is an (only) element of x. The fact that you append it to x doesn't change y in any way. It is still the same object.

I would appreciate any help finding a way around this.

It depends on what do you want behavior to be. If you want "value semantics", that is, for y to be copied when appending it to x, just say so:

x.append(y.copy())
Veky
  • 2,646
  • 1
  • 21
  • 30