Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Lists - Is it efficient to keep overwriting their references?

Tags:

I know that Python's garbage collection system can be unpredictable, so I want to understand what the best way is of dealing with continuously overwriting the reference to a list with a new list.

For instance, I am trying to write up a method for updating a priority queue. The parameters for this abstract method is a tuple with the priority and corresponding element, and a list which acts as the container which needs updating. I have a single variable that is initially an empty list keeps track of all tuples that are added to it. I have a long list of elements that need to be added, so I am constantly re-referencing the one variable with list slices (therefore not updating the reference itself). How negligible is the garbage created over a long time due to the old data?

like image 674
Samer Kadih Avatar asked Jul 19 '18 01:07

Samer Kadih


1 Answers

You shouldn't worry about continuously overwriting the reference to an object with a new one since Python's garbage collection is actually extremely predictable, as demonstrated below:

>>> class A(object):
...     def __new__(cls):
...         new = super(A, cls).__new__(cls)
...         print('creating %s' % new)
...         return new
...     def __del__(self):
...         print('deleting %s' % self)
...
>>> a=A()
creating <__main__.A object at 0x018418F0>
>>> a=A()
creating <__main__.A object at 0x01841930>
deleting <__main__.A object at 0x018418F0>
>>> a=A()
creating <__main__.A object at 0x01841970>
deleting <__main__.A object at 0x01841930>
>>> a=A()
creating <__main__.A object at 0x01841910>
deleting <__main__.A object at 0x01841970>
>>>
like image 64
blhsing Avatar answered Sep 28 '22 17:09

blhsing