Best way to iterate and modify a deque in Python

Viewed 32

My deque is an array like this [ [2,3], [11,7], [15,13] ] which has one item popped off the left each loop and then reinserted. Every once in a while a new item is inserted. The first item in each pair is in ascending order

I need to implement this algorithm but don't know how I can insert/swap items:

new_item = [11,5]

append=False  #used when failed to insert item and it needs to be appended instead.
for item in deque:
    if new_item[0] <= item[0]:
        #ordered position found so insert item
        insert_before(item, new_item)     #<----- is something like this possible?
        break
    elif new_item[0] == item[0]:
        #position found but already taken
        if new_item[1] < item[1]:
            #swap with current item for the largest
            swap( new_item, item )        #<----- is something like this possible?
        #increment new_item position and continue search
        new_item[0] += new_item[1]
else:
    #didn't find position and break therefore need to append item
    append=True
if append:
    deque.append(new_item)

So in this example the new array would be [ [2,3], [11,5], [15,13], [18,7] ]

Can I do that insert_before or do I have to loop through with an index and then insert?

Can I "swap" an item like that or does it not work?

0 Answers
Related