My code looks like this, where heap
is a list
:
heap[0] = heap.pop()
The problem is it does not work when popping the only item. According to python wiki, popping last element is O(1). (I also want to remove the last element)
So far what I've come up with:
last_element = heap.pop() # I don't want to catch potential IndexError here
try:
heap[0] = last_element
except IndexError:
heap.append(last_element)
which is a lot longer
or this
if len(heap) != 1:
heap[0] = heap.pop()
which should be slower.
Is there a more pythonic way to do this? Internally python maybe does not even resize the array.
UPDATE: I need O(1) access to elements at given indeces (so it cannot be a linked list).