Home > Mobile >  List updating itself after variable appending in it changes
List updating itself after variable appending in it changes

Time:09-21

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?

CodePudding user response:

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...

  • Related