-2

Hey guys/girls total noob over here, but I can't for the life of me figure out why this function isn't sorting out all the values below 40. I'm really surprised because it's such a basic task, even for me but I've been staring at it for a while now and can't figure it out.

def sort(list):
    list.sort()
    for num in list:
        if num < 40:
            list.remove(num)

return list

print (sort([-31, 0, 5, 76, 12, 32, 4, 88]))

Output : [0, 5, 32, 76, 88]

Ali AzG
  • 1,861
  • 2
  • 18
  • 28
  • removing elements from a list while iterating causes iteration to skip elements, see my suggested duplicate for other solutions – Adam.Er8 Nov 07 '19 at 10:21

1 Answers1

0

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.

Szzaass
  • 1,090
  • 1
  • 7
  • 10