How to eliminate all strings from a given list in Python?
For example, if I have
list = ['hello', 1, 2, 3, 4, 'goodbye', 'help']
I'd want the outcome to be
[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]
Either use list comprehension as @user3100115 or use the "lisp/lambda approach"
>> l = [1, 2, 'a', 'b']
>> list(filter(lambda a: isinstance(a, int), l))
[1, 2]
By the way, do not name your variable list. It is already a python function. :)
lambda to use filter, then a listcomp or genexpr is always going to be faster and equally succinct (assuming a short name for the variable being iterated). Please don't use map/filter if you need a lambda to make them work.My way how I'd do that:
values = [v for v in values if type(v) is not str]
That'd be similar to this written out (but faster):
new_values = []
for v in old_values:
if type(v) is not str:
new_values.append(v)
I renamed your "list" to "values" because list already exists in python. It's the class name for the list type.