L
is initialized to a list. Then add reference a L1
to L
. Now both the L1
and L
variables should point to same object. So why does sys.getrefcount()
still return 1?
>>> L = [1,2,3]
>>> L1 = [1,2,3]
>>> L==L1
True
>>> L is L1
False
>>> sys.getrefcount([1,2,3])
1
>>> L1 = L
>>> L1 is L
True
>>> sys.getrefcount([1,2,3])
1
You are creating new lists. Each new list has just a single referrant, the reference held by the argument to the sys.getrefcount()
function.
If you want to see the reference count for the list objects that the L
and L1
names reference, then you'll have to pass those names into the sys.getrefcount()
function:
>>> import sys
>>> L = [1,2,3]
>>> sys.getrefcount(L)
2
>>> L1 = L
>>> L1 is L
True
>>> sys.getrefcount(L)
3
>>> sys.getrefcount(L1)
3
L
starts with 2 references: the L
name itself, and the argument to sys.getrefcount()
. When you then also assign the object to L1
, there is now one more reference to it.
Don't get confused between the syntax that produces the list value, and what is stored in memory. If you imagine having two identical shopping bags, and you go to the store and put a packet of cookies in one bag, and another packet of cookies from the same type in the other bag, are the two bags the same thing? They look the same, you could eat those cookies and they'd taste the same, but they are still two separate bags with cookies in them. If someone stole one of those bags you'd still have the other bag to eat the remainder of the cookies.
Writing [1, 2, 3]
in Python tells Python to make a new shopping bag (list) and put in some cookies (integer numbers). That new bag looks the same as the other bags (lists), so they have the same value (==
returns True
), but they are not the same single bag (is
does not return True
).
Now, put post-it notes on those bags, giving the bags names. Write L
on one note, stick it on one bag. Write L1
on the other note, stick it on the other bag. Their values are still the same, but when you ask Python if L
and L1
are the same bag, then you know they are not, the post-it notes are stuck to two different bags. But what if you were to move that L
post-it note from the one bag it was stuck to, and move it to the other bag that has L1
stuck to it? Now you have two post-it notes on the same bag, so L is L1
is true now.
sys.getrefcount()
tells you how many post-it notes there are stuck to the bags. But you need to tell it about post-it notes, not new bags.
And finally, you can put those bags inside other bags, or put the bags inside labeled drawers in a filing system (or dict
objects), and getrefcount()
would count those too. Because post-it notes are not the only way to track shopping bags, right?