Weird behavior in search in a list

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


"Su Y" <suyuancn at gmail.com> wrote in message 
news:1175169306.021284.46270 at e65g2000hsc.googlegroups.com...
On 3ÔÂ29ÈÕ, ÏÂÎç7ʱ51·Ö, "Su Y" <suyua... at gmail.com> 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
          else:
             break
>     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
j





More information about the Python-list mailing list