You don't present the entire code for the class here, but the usage of
self and the doctests within the docstring indicates that you are actually using a class. As such my first order would be that in the initialisation of the class you always create the
_items list, which would remove the need to check whether there are elements or not when adding elements.
i = len(self._items) to terminate the loop is a hackish solution. It would be better to use
break instead. But
for (and actually
try ... except) allows for the usage of
else which can help out in this particular case. In short, if the loop terminates ordinarily, the
else part is executed, if you
break out of it, it'll not be executed.
In stead of doing the
while i < len(self._items) loop, which requires calculating the length multiple times, and doesn't look to Pythonic, I would suggest using
for i, item in enumerate(self._items). This loop construct loops over all the elements (if any) and gives the index of the current element (due to the use of
Lastly, naming the method
additems() when you only add one element is misleading and not following standards. A better name would be
This leads to the following code:
self._items = 
def add_item(self, new_item):
"""Add items into queue at correct place."""
for i, item in enumerate(self._items):
if new_item < item:
pq = PriorityQueue()
if __name__ == '__main__':
I'm sorry that the environment I tested this in doesn't support doctests, but this does output the correct list of
['blue', 'green', 'red', 'yellow'].