Consider we have a list ABC which has contents as [1,2,3,4] & we copy the list data to another one says XYZ. What we see after copying a list to another is that in case we make changes to XYZ they too get reflected onto ABC. Why does this happen?
See below, after copying ABC to XYZ I have deleted the 2nd index of XYZ and fetched the XYZ & ABC details. We see the changes made in XYZ too occur in ABC
Let’s see what happens in the backend to get clarification
- When I store a data in variable ABC it does not actually contain the values but contains a reference to that list.
- So, when we copy ABC list to XYZ we do not copy the values but the reference link.
- Hence when we manipulate the data using XYZ list the changes are reflected for ABC as well.
- So, if you do not want this to happen use list keyword while copying the data. Example: XYZ = list (ABC)
- Now see the below results:
Hope these details provide you a clear picture of what happens at the back-end when we copy lists in Python.