Let's quickly resolve confusion surrounding an Object and a Variable :
Let's say you've a list as -
fruits = ['apple','orange','grape']
When such a list is created, the fruits is a variable holding the location of memory where the list exists.
The location can be checked with the help of the following function:
id(fruits)
Now when you try to update the list as:
fruits = ['mango','banana','Tomato']
(It's no typo, Tomato is actually a fruit)
You think that you've updated the earlier existing list with new values, but instead you've have actually created a new python object altogether and it's memory location is fed to the variable fruits.
This can be verified by checking -
id(fruits)
Clearly there would be stark contrast between the memory value obtained previously and the latest one.
If no other variable is now referring to the older list, then python's garbage collector will auto-delete it from memory.
Now if you really want to update the list with fresh values, then use the following code instead :
fruits.clear() #It clears all elements from the existing list
fruits.extend(['mango','banana','Tomato']) #populates list with new elements
Hope this was helpful for you!
Top comments (0)