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

23rd Sep 2019, 9:48 PM
Onimisi
Onimisi - avatar
4 Réponses
+ 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.
23rd Sep 2019, 10:01 PM
Thoq!
Thoq! - avatar
+ 1
Thanks
23rd Sep 2019, 10:05 PM
Onimisi
Onimisi - avatar
+ 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[:])))
23rd Sep 2019, 10:27 PM
rodwynnejones
rodwynnejones - avatar
+ 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
1st Sep 2020, 4:57 PM
teemran
teemran - avatar