Your function is sorting out the values alright.
The problems is that you're messing with the list iterator when you remove items during the iteration. You cannot remove elements from a list while looping through its elements.
What happens is that when you remove an element you don't reset the iterator and, behind the scenes, it uses an index to iterate, so when you remove the item you shift the next item one index back and tell loop moves forward, skipping a few items.
[-31,0,5,76,12,32,4,88]
# first iteration: i = 0, removes -31
[0,5,76,12,32,4,88]
# second iteration: i = 1, removes 5
See what happened?
An alternative is to use a while:
while len(list) > 0 and list[0] < 40:
list.pop(0)
Another alternative is to, since you sorted the list, find the index for the greater number below 40 and then remove all elements before it in a single blow:
max_b40_index = None
for (e, e_index) in enumerate(list):
if e >= 40: break
max_b40_index = e_index
return list[:max_b40_index+1]
The list[:n]
code returns a subset from index n to the end of the list.
Oh, be sure to check that max_b40_index
isn't none. You might have a list without any numbers below 40.