2

I'm totally new to Python and I'm sure I'm missing something simple, I want to remove all Strings.

def filter_list(l):
for f in l:
    if isinstance(f, str):
        l.remove(f)
return l

print(filter_list([1,2,'a','b'])) 

The output I get is:

[1,2,'b']

3 Answers 3

2

Your error came from removing items from list in iteration and at last, you don't check the last item (for more details read this : How to remove items from a list while iterating?) For this approach remove items with list comprehension.

def filter_list(l):
    return [f for f in l if not isinstance(f, str)]

print(filter_list([1,2,'a','b'])) 
# [1, 2]
Sign up to request clarification or add additional context in comments.

Comments

2

Often when we need to filter a sublist from a list given a condition, you'll see this sort of syntax (i.e. list comprehension) quite commonly, which serves to do the exact same thing. It's up to you which style you prefer:

a = [1,2,'a','b']
b = [x for x in a if not isinstance(x, str)]
print(b)  # [1, 2]

Comments

0

so you can do something like

def filter_list(l)
for f in l:
  if type(f) == str:
    l.remove(f)
return l

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.