When a tuple is reassigned to a new address, is the value at the old address cleared?

Viewed 144

I was trying to figure out how memory allocation works with regards to a tuple in python.

skills = ("Python", "pandas", "scikit-learn")
print(id(skills))

This gives me a value of 140555133913704

I modify this tuple to create a new one

skills += ("ml","dl")
print(id(skills))

The new address is 140555133738680

Is the tuple object at 140555133913704 deleted and the address cleared?

Is modifying a tuple less or more space efficient as compared to modifying a list?

2 Answers

everything besides primitives in python is an object so when you type:

skills = ("Python", "pandas", "scikit-learn")

you are creating a tuple object and the reference to that is going to be stored in the skills variable you declared.
in the second step, you make another tuple object with the value of the last tuple in addition to "ml" and "dl" now you have the new object's reference in your skills variable. what happened to the last one? well, it is still there but now it is an unreferenced object and the python garbage collector will clear that.
about lists, a list in python is also an object and is stored with the data of it and a "len" attribute which indicates the length of the array so if you append something to a list this will happen again although lists are mutable objects! (I actually got suspicious about this and tried it myself and it changed:) ) so again, the garbage collector will remove the unreferenced object after a while.

>>> list = [1,2,3]
>>> id(list)
2214374343624
>>> list = list + [2,3]
>>> list
[1, 2, 3, 2, 3]
>>> id(list)
2214472730440

It is because tuples are immutable and they cannot be changed. In your example adding tuple to a tuple will create a new tuple and assigns it to same name. It will not change the tuple object originally referenced by that name.

  • The tuple object at 140555133913704 will not be deleted. It will have previous value i-e, ("Python", "pandas", "scikit-learn")
  • Tuples are more space-efficient than lists. Lists are over-allocated to make appending faster.
Related