Python Internals
When we create a variable in Python and assign some data to it an object of the data gets created in memory and the variable points to it. So when we assign the same data value to another variable it references the same data. (Everything in Py is an object)
username = "Om"
>>> password = "Om"
>>> id(username)
3015234535568
>>> id(password)
3015234535568
>>> username2 = username
>>> username2
'Om'
>>> username = 'Hello'
>>> username2
'Om'
This behavior is specific to small integers in Python (usually from -5 to 256), which are singletons and are always stored in memory with the same address.
Same is not true with mutable datatypes like List. Even if the values are same of 2 lists, Python creates a seperate copy for each list.
>>> list1 = [1,2,3,4]
>>> list2 = [1,2,3,4]
>>> list1 is list2 #Seperate copies created
False
>>> copy_list1 = list1 #Seperated copies not created as reference is given
>>> copy_list1
[1, 2, 3, 4]
>>> list1[0] = 99
>>> list1
[99, 2, 3, 4]
>>> copy_list1
[99, 2, 3, 4]
Conclusions:
Variables containing mutable datatypes in Python have an object created once and all future references point to that object whereas in immutable datatypes like list seperate copies of data is created for every reference.
Subscribe to my newsletter
Read articles from Om Pawaskar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by