Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eliminate all strings from a list

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]

like image 225
SlashedDelta Avatar asked May 03 '16 12:05

SlashedDelta


2 Answers

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]
like image 158
styvane Avatar answered Nov 14 '22 23:11

styvane


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]
like image 37
Byte Commander Avatar answered Nov 14 '22 23:11

Byte Commander