0

I would write a little function to check if a string in a list, and when yes, the string should remove out of the List.

this is my code

def str_clearer(L):
    for i in L:
        if i == str:
            L.remove(i)
        else:
            pass
    print(L)
    return L

L = [1, 2, 3, "hallo", "4", 3.3]

str_clearer(L)

assert str_clearer(L) == [1, 2, 3, 3.3]

but it make nothing with the List.
if i make it so that it make a new List with all int or float, he make same nothing.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Arresh
  • 11

2 Answers2

2

Python built-in function, isinstance(), can be used here.

The following approach is similar to yours.

In[0]: def remove_str(your_list):
           new_list = []    
           for element in your_list:
           if not(isinstance(element, str)):
               new_list.append(element)
           return new_list

In[1]: remove_str([1, 2, 3, "hallo", "4", 3.3])
Out[1]: [1, 2, 3, 3.3]

This can be much shorter, though.

In[2]: mylist = [1, 2, 3, "hallo", "4", 3.3]
In[3]: result = [x for x in mylist if not(isinstance(x, str))]
In[4]: print(result)
Out[4]: [1, 2, 3, 3.3]
Taro Kiritani
  • 724
  • 6
  • 24
1

Type checking can be done with isinstance. This could actually be done pretty elegantly in a list comprehension:

result = [x for x in L if not isinstance(x, str)]
Mureinik
  • 297,002
  • 52
  • 306
  • 350