Weird behavior in search in a list

Josh noone at
Thu Mar 29 14:17:53 CEST 2007

"Su Y" <suyuancn at> wrote in message 
news:1175169306.021284.46270 at
On 3ÔÂ29ÈÕ, ÏÂÎç7ʱ51·Ö, "Su Y" <suyua... at> wrote:
> hi all,
> I can't understand how this code work, its behavior is really weird
> for me...
> I want find the first number in extend[] which is larger than num, soI 
> wrote:
> def find(num):
>     count=0
>     for elem in extend:
>         if elem<num:
>             count+=1
>     return count
you need to break out of the loop when you first encounter num>elem. The 
reason it works in your sorted list scenario is because elem will be > num, 
always, after some point. It won't be in your unsorted list.

I've added the else: break in your code above

More information about the Python-list mailing list