Finding the insertion point in a list

7stud bbxx789_05ss at yahoo.com
Sat Mar 17 12:57:56 EDT 2007


On Mar 17, 4:12 am, "Martin Blume" <mbl... at socha.net> wrote:
> "7stud" schrieb
>
>
>
> > How about:
>
> > -----------
> > x = [0, 100, 200, 1000]
> > y = -1
> > inserted = False
>
> > for i in range(len(x)):
> >         if(y <= x[i]):
> >                 x.insert(i, y)
> >                 inserted = True
> >                 break
> > if(not inserted): x.append(y)
>
> > print x
> > ------------
>
> You can get rid of the sentinel "inserted" using the
> else clause of the for loop:
>
> for i in range(len(x)):
>         if (y <= x[i]):
>                 x.insert(i, y)
>                 break
> else: x.append(y)
>
> Python is cool :-)
>
> IMHO. HTH.
> Martin

for-else?  Neat.




More information about the Python-list mailing list