Reputation: 11
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.
Upvotes: 0
Views: 153
Reputation: 724
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]
Upvotes: 2
Reputation: 311518
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)]
Upvotes: 1