Weird behavior in search in a list

Michael Bentley michael at jedimindworks.com
Thu Mar 29 08:22:50 EDT 2007


On Mar 29, 2007, at 6:51 AM, Su Y wrote:
>
> I want find the first number in extend[] which is larger than num, so
> I wrote:
> def find(num):
>     count=0
>     for elem in extend:
>         if elem<num:
>             count+=1
>     return count
>
> I found that if extend[] is monotonous, like [1.1, 2.3, 3.2, 4.5,
> 5.6],
> it works fine: find(4) returns 3, extend[3] is 4.5.
> But, if extend[] is not monotonous, like [1.1, 2.3, 3.2, 4.5, 5.6,
> 4.6, 3.4, 2.1, 0.3],
> find(4) returns 6, extend[6] is 3.4!
>
> what's going on here? I really can't understand....

find() loops through the list, and every time it finds a value less  
than num it increments count.  So in your second example the values  
1.1, 2.3, 3.2,  3.4, 2.1, and 0.3 are all less than 4, which means  
count will be 6.

As you learned, a sorted list behaves as you expect.  So one approach  
is to sort your list first.  But another perhaps better approach is  
to do something like:

def find(num):
	# check to make sure there *is* a value greater than num
	if max(extend) > num:
		# then return the smallest value that is greater than num
		return min([x for x in extend if x > num])
	else:
		return None

Hope this helps,
Michael



More information about the Python-list mailing list