Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading