- Reference counting is one of the memory management technique in which the objects are deallocated when there is no reference to them in a program.
- Every object in Python has a reference count and a pointer to a type, in the struct PyObject.
- Variables in Python are just the references to the objects in the memory.
- It will be increased when:
- if you assign it to another variable
- It will also increase if you pass the object as an argument:
total = sum(numbers) - The reference count will increase if you include the object in a list:
matrix = [numbers, numbers, numbers] - It will decrease when:
- Once the variable referencing to it is set to None or if it gets deleted during the execution of the program, then the reference count reduces.
numbers = [1, 2, 3]
# Reference count = 1
more_numbers = numbers
# Reference count = 2
sys.getrefcount(object) # passing object will increase +1