0
Removing a long range of strings from a list in python
Let's say I have a long list of items having both integers, floats and strings and I wish to remove only the strings and leave the integers and floats in the list. Is there a function to do it at once or do I have to manually remove each item using the remove function list.remove(obj) like this? To me it's quite a whole lot of work
4 Antworten
+ 2
This is how I would do it:
https://code.sololearn.com/cfU8dxCJU3f0/?ref=app
It is usually better to create a new list because iterating over an existing one is kind of dangerous.
+ 1
Thanks
+ 1
myarr = [1, 2, 3, 4, 'blah', 2.33, 'blah', 4.66, 'blah', 34, 'blah', 4, 'blah']
print(list(filter(lambda x: isinstance(x, (int, float)), myarr[:])))
+ 1
You can also create an empty list variable, use for loop to iterate over each item in the list that is int to append it to the empty lits variable.
Like this:
https://code.sololearn.com/cfK1794BW3Pw/#py