I have a list for example
list = [1,2,3,'t',4,5,'fgt',6,7,'string']
and I want to use the filter() function to remove all the strings to leave just numbers.
I can do it the normal method, but I cant do it with the filter method...any tips?
so:
list(filter(type(i)==str,a)))
wouldn't work...I tried to use it, but that still doesn't work:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
list(filter(type(a[-1])==str,a))
TypeError: 'bool' object is not callable
While you could use filter for this, don't. You'd need a lambda function to do it, and it would be both slower and less readable than an equivalent list comprehension or generator expression. Instead, just use the listcomp or genexpr:
old_list = [1,2,3,'t',4,5,'fgt',6,7,'string']
new_list = [x for x in old_list if isinstance(x, (int, float))]
# or to remove str specifically, rather than preserve numeric:
new_list = [x for x in old_list if not isinstance(x, str)]
That's much more straightforward than the filter+lambda equivalent:
new_list = list(filter(lambda x: isinstance(x, (int, float)), old_list))
As noted in COLDSPEED's answer, to be generally accepting of all "number-alikes" you should actually use isinstance with numbers.Number; using (int, float) handles the literal types, but wouldn't handle complex, fractions.Fraction, decimal.Decimal, or third-party numeric types.
If you're looking for a filter, you can shape your lambda to be a bit more elegant.
from numbers import Number
new_list = list(filter(lambda x: isinstance(x, Number), old_list))
numbers.Number is an injected superclass of int and float, and complex. For real types, use numbers.Real instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With