List updating itself after variable appending in it changes

Question:

mainData = []
data = []
newEntry = [1,2,3]
data.append(newEntry)
mainData.append(data)
print(mainData)
anotherEntry = [4,5,6]
data.append(anotherEntry)
thirdEntry = [7,8,9]
data.append(thirdEntry)
print(mainData)

OP =>
[[[1, 2, 3]]]
[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]

Why my ‘mainData’ is changing when i’m only appending data in ‘data’ variable?

Asked By: Dhruv Patel

||

Answers:

Because it also copy the indexes; below code is the way to go;

mainData = []
data = []
newEntry = [1,2,3]
data.append(newEntry)
mainData.append(data.copy()) # change here
print(mainData)
anotherEntry = [4,5,6]
data.append(anotherEntry)
thirdEntry = [7,8,9]
data.append(thirdEntry)
print(mainData)

Hope it Helps…

Answered By: Sachin Kohli
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.