简体   繁体   中英

List updating itself after variable appending in it changes

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM