I would like to know why this code prints 4
instead of 3
. Where is the fourth reference?
import sys
def f(a):
print(sys.getrefcount(a))
a = [1, 2, 3]
f(a)
We can make sense of this in steps:
import sys
print(sys.getrefcount([1, 2, 3]))
# output: 1
import sys
a = [1, 2, 3]
print(sys.getrefcount(a))
# output: 2
import sys
def f(a):
print(sys.getrefcount(a))
f([1, 2, 3])
# output: 3
import sys
def f(a):
print(sys.getrefcount(a))
a = [1, 2, 3]
f(a)
# output: 4
So to reiterate:
a
f
functionf
takesgetrefcount
functionThe reason for no fifth reference, from the parameter getrefcount
takes, is that it's implemented in C, and those don't increase the reference count in the same way. The first example proves this, since the count is only 1 in that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With