Max Andersson
Max Andersson

Reputation: 135

filtering out strings in a list Python

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']

Upvotes: 2

Views: 73

Answers (3)

Thales
Thales

Reputation: 59

so you can do something like

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

Upvotes: 0

I'mahdi
I'mahdi

Reputation: 24049

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]

Upvotes: 2

Jamie.Sgro
Jamie.Sgro

Reputation: 882

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]

Upvotes: 2

Related Questions