0
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?

  • Does this answer your question? [How do I clone a list so that it doesn't change unexpectedly after assignment?](https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment) – Mechanic Pig Sep 21 '22 at 07:16
  • No, i'm not assigning 'mainData' list to another list. I'm just appending 'data' variable in mainData. While appending data in 'data' , my mainData list automatically gets updated. – Dhruv Patel Sep 21 '22 at 07:21
  • There is no difference between them. Whether it is adding or allocating, what you give them is the list itself, not the copy. – Mechanic Pig Sep 21 '22 at 07:23

1 Answers1

0

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

Sachin Kohli
  • 1,956
  • 1
  • 1
  • 6
  • Yes, it worked but i want to know the reason why my 'mainData' is changing while making changes to 'data'.Thanks. – Dhruv Patel Sep 21 '22 at 07:27
  • Perhaps you need to understand the difference between Deep vs Shallow copy... idea is not to copy the reference/index too along with values while assign objects... – Sachin Kohli Sep 21 '22 at 07:31