Search

Curious case of Lists subset and copy of list subset in Python - & why you should understand this ?

Updated: Sep 2, 2020

Assumption before you start is - that you understand below concepts, if not - its worth a quick detour to below links:



Proceed if you know - what happens as a single variable is assigned references to objects? Else read above three articles real quick and come back.


If you know what happens as a single variable is assigned reference to an object then - let’s introduce another variable into our interaction and watch what happens to its names and objects:



     >>> x = 10
     >>> y = x


If above two statements are executed in python - something like this happens.




The second command causes Python to create the variable y, the variable x is being used and not assigned here, so it is replaced with the object it references (10), and y is made to reference that object. The net effect is that the variables x and y wind up referencing the same object (that is, pointing to the same chunk of memory).


This scenario in Python—with multiple names referencing the same object—is usually called a shared reference or a shared object. Note that the names x and y are not linked to each other directly when this happens, in fact - there is no way to ever link a variable to another variable in Python! Rather, both variables point to the same object via their references.


Next, suppose we extend the example with one more statement:



   >>> x = 10
   >>> y = x
   >>> x = 'bharath'


As with all Python assignments, this statement simply makes a new object to represent the string value 'bharath' and sets a to reference this new object. It does not, however, change the value of y, y still references the original object, the integer 10. The resulting reference structure, looks something like this.






The same sort of thing would happen if we changed b to 'bharath' instead—the assignment would change only y, not x. This behavior also occurs if there are no type differences at all. For example, consider these three statements: