my question is how to eliminate all strings from a list, for example if I have list=['hello',1,2,3,4,'goodbye','help']
and the outcome to be list=[1,2,3,4]
You need to use isinstance
to filter out those elements that are string. Also don't name your variable list
it will shadow the built in list
>>> from numbers import Real
>>> lst = ['hello', 1, 2, 3, 4, 'goodbye', 'help']
>>> [element for element in lst if isinstance(element, Real)]
[1, 2, 3, 4]
or
>>> [element for element in lst if isinstance(element, int)]
[1, 2, 3, 4]
or
>>> [element for element in lst if not isinstance(element, str)]
[1, 2, 3, 4]
You can do that using isinstance
, but unlike the other answer by user3100115 I would blacklist types that you don't want instead of whitelist only a few types. Not sure which would be more suitable for your special case, just adding that as alternative. It also works without any imports.
lst = ['hello', 1, 2, 3, 4, 'goodbye', 'help']
filtered = [element for element in lst if not isinstance(element, str)]
print(filtered)
# [1, 2, 3, 4]
Instead of a list comprehension, you could also use the filter
builtin. That returns a generator, so to directly print it, you have to convert it into a list first. But if you're going to iterate over it (e.g. using a for
-loop), do not convert it and it will be faster and consume less memory due to "lazy evaluation". You could achieve the same with the example above if you replace the square brackets with round brackets.
lst = ['hello', 1, 2, 3, 4, 'goodbye', 'help']
filtered = list(filter(lambda element: not isinstance(element, str), lst))
print(filtered)
# [1, 2, 3, 4]
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