Finding the insertion point in a list
Martin Blume
mblume at socha.net
Sat Mar 17 06:12:40 EDT 2007
"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
More information about the Python-list
mailing list