Weird behavior in search in a list
khemkaamit at gmail.com
Thu Mar 29 14:15:22 CEST 2007
On 29 Mar 2007 04:51:00 -0700, Su Y <suyuancn 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, so
> I wrote:
> def find(num):
> for elem in extend:
> if elem<num:
> return count
> I found that if extend is monotonous, like [1.1, 2.3, 3.2, 4.5,
> it works fine: find(4) returns 3, extend 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 is 3.4!
> what's going on here? I really can't understand....
Actually your function "find" returns the number of elements in list
extend, which are smaller than the argument. Perhaps you wanted to
'break' when once the condition is met.
for elem in extend:
if elem>num: break
Btw a concise way could be:
for i,x in enumerate(extend):
if x>num: return i
Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
More information about the Python-list