Loop ending

My loop seems to terminate after one iteration. What am I doing wrong?

def filter_list(l): i = 0 while i < len(l): if type(l[i]) != int: l.remove(l[i]) i += 1 return l

Hello @jakerslordofdarkness, welcome to the forums! It seems to work for me. What’s the output you’re getting, and what’s the desired output?

You are removing elements from the list while iterating through it by index, which is a bit tricky.

Consider this:
if you remove the element at index 3, then what was previously at an index of 4 will now be at index 3.
So if you remove something at index 3, the next element you should check will have an index of 3.
Therefore you should be increasing the index you’re checking only when you don’t remove something.

You could accomplish this by putting the i += 1 inside an else block.

def filter_list(l):
    i = 0
    while i < len(l):
        if type(l[i]) != int:
            l.remove(l[i])
        else:
            i += 1
    return l

print( filter_list([0,1,'2','3',4]) )
2 Likes

Hello! I’m trying to remove all none integers from a list ie strings.

filter_list([1, 2, ‘a’, ‘b’] would return [1, 2]. On my machine it is only removing the first string.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.