

Instead, think of it as ‘give b the additional name a’. If there are variables on both sides, you can’t really know that. Never think that ‘a = b’ in Python means ‘copy b to a’. Method 3Īs it has already been answered, I’ll simply add a simple demonstration: Therefore, it creates a new list with all the data contained in the first one, but both can be altered without changing the other. The default values for are 0 and the end of the list, so it copies everything. However, when you do newList = oldList, it “slices” the list, and creates a new list. NewList = oldList would create two different variables that point to the same object, therefore, changing oldList would also change newList. Like NXC said, Python variable names actually point to an object, and not a specific spot in memory. > # Updating the new list to point to something new is not reflected # change reflected when you access that element through the > # Updating one of the elements through the new list sees the > # The shallow copy makes a new list pointing to the old elements > # The initial list has two elements containing 'aaa' and 'bbb' New list is now referring to a different object. Reference in the new list can be seen to not reflect in the old list, as the Seen when the object is accessed through the old list. Its state updated by reference through the old list, and the updates can be List being made with copies of the old objects. Running it in a python shell gives the following transcript. # Updating the new list to point to something new is not reflected

# Updating one of the elements through the new list sees the # The shallow copy makes a new list pointing to the old elements

# The initial list has two elements containing 'aaa' and 'bbb'
Slice back of list code#
The code snippet below shows a shallow copy in action. However, if you do something to the list members, both lists still refer to them, so the updates will show up if the members are accessed through the original.Ī Deep Copy would make copies of all the list members as well. This means that operations on the copy do not affect the structure of the original. Shallow copies the list, making a copy of the list structure containing references to the original list members. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible. Please note that all the answers may not help you solve the issue immediately. Thank you for visiting the Q&A section on Magenaut.
