The Python Book
 
bisect insert
20151026

Insert an element into an array, keeping the array ordered

Using the bisect_left() function of module bisect, which locates the insertion point.

def insert_ordered(ar, val):
    i=0
    if len(ar)>0:
        i=bisect.bisect_left(ar,val)
    ar.insert(i,val)

Usage:

ar=[]
insert_ordered( ar, 10 )
insert_ordered( ar, 20 )
insert_ordered( ar, 5 )
 
Notes by Willem Moors. Generated on momo:/home/willem/sync/20151223_datamungingninja/pythonbook at 2019-07-31 19:22