I do not understand why my 3 from y is being deleted in the following code. I assume it is some aliasing problem, but is there any way to let y retain the number when x has it removed?
x = []
y = []
for i in range (10):
if i == 5:
y.append(x)
del x[3]
x.append(i)
print (x)
print (y)
Output:
x = [0, 1, 2, 4, 5, 6, 7, 8, 9]
y = [[0, 1, 2, 4, 5, 6, 7, 8, 9]]
You’ll have to append a copy of
xto y:y.append(x)appends the list that is referenced byx, soyessentially is[x]. Because it isxthat is contained byy, and not any other list, you are changing the value ofywhen you changex.Also, if
xis a nested list, you might want to consider taking a deepcopy ofxlike so:So that each of the nested lists are copies, and not the same lists in
x.