blog
blog copied to clipboard
Wrong list method (or approach) used in code example
There is a flaw in this article about Queue Data Structures
https://blog.boot.dev/python/queue-data-structure-python/
In the first code example, the push() method uses insert() for placing new items at the index 0 of the list, and the pop() method uses the pop() method of python lists to remove the item at the end of the list, the insert() method for python lists is inneficient because you have to shift all the items to the right. This is all correct, BUT, it is not the right approach for building a queue, there is a much better way to do this
The alternative (correct) way is to think about it in reverse: The new items enter at the end of the list, and the last item that leaves the queue is the one placed at index 0 of the list
...
# I renamed both methods to avoid any possible confusion to what I want to explain next
def enter(self, item):
# renamed from push() in the original code
self.items.append(item)
def leave(self):
# renamed from pop() in the original code
if len(self.items)==0:
return None
return self.items.pop(0)
...
Technically, the performance problem still exist, because it is passed to the leave() method of the class when the item leaves, and this because the pop() method also has to do the same gymnastics that the insert() does. However, in a real life situation, this is how you want it to be, because in real life, you have control of when an item leaves a queue, but not exactly when it enters, so the computation cost is actually manageable only on one side, not the other
For example, network requests
In network request you do not have control of when something from the request enters a certain queue for a certain task, because you do not have control of the clients, but you definitively have control of how the next item that is about to leave the queue