From listobject.h
I read this line:
"PyList_SetItem does not increment the new item's reference count, but does decrement the reference count of the item it replaces, if not nil. It does decrement the reference count if it is not inserted in the list. Similarly, PyList_GetItem does not increment the returned item's reference count."
But when i tested reference count of the element got increased.
>>> a = 'abc'
>>> sys.getrefcount(a)
3
>>> ls = [1,2]
>>> ls.append(a)
>>> ls
[1, 2, 'abc']
>>> sys.getrefcount(a)
4
>>> ls.insert(1,a)
>>> sys.getrefcount(a)
5
>>>
Please correct me if i wrong or explain me how it is ?
The implementation of
append
knows about this quirk ofPyList_SetItem
and deals with the reference count increment.This is really the only way it could work. Reference counting is really a facet of the implementation, and --
getrefcount
notwithstanding -- not something Python programmers have to deal with.To put it another way, you only need to worry about whether an API steals a reference or makes a new reference if you are writing an extension in C. If you stick to Python, you are safe.