Finding the insertion point in a list

kyosohma at gmail.com kyosohma at gmail.com
Fri Mar 16 20:37:10 CET 2007


On Mar 16, 2:32 pm, "Paul McGuire" <p... at austin.rr.com> wrote:
> On Mar 16, 12:59 pm, tkp... at hotmail.com wrote:
>
>
>
> > I have an ordered list e.g. x = [0, 100, 200, 1000], and given any
> > positive integer y, I want to determine its appropriate position in
> > the list (i.e the point at which I would have to insert it in order to
> > keep the list sorted. I can clearly do this with a series of if
> > statements:
>
> > if y<x[1]:
> >     n = 0
> > elif y < x[2]:
> >     n = 1
> > elif y < x[3]:
> >     n = 2
> > else:
> >     n = 3
>
> > Or with a generator comprehension
> > n  = sum ( y>x[i] for i in range(len(x)) ) - 1
>
> > But there  has to be a cleaner way, as the first approach is unwieldy
> > and does not adapt to changing list lengths, and the second is not
> > obvious to a casual reader of the code.
>
> > My list will typically have 2 to 5 items, so speed is not a huge
> > issue. I'd appreciate your guidance.
>
> > Sincerely
>
> > Thomas Philips
>
> List "will typically have 2 to 5 items"?  Keep it simple!
>
> x.append(y)
> x.sort()
>
> -- Paul

I thought doing an append and sort was a good idea too, but the
question entailed knowing the insertion point, so I skipped it.
Thanks!




More information about the Python-list mailing list