I have a list which contains a mix of strings and numbers eg
old_list = [23, 35, string, 42, string]
I would like list to look like this
new_list = [23,35,45]
Is there a simple way to do this?
I have a list which contains a mix of strings and numbers eg
old_list = [23, 35, string, 42, string]
I would like list to look like this
new_list = [23,35,45]
Is there a simple way to do this?
Use a list comprehension to filter on type:
new_list = [value for value in old_list if isinstance(value, int)]
This picks out just integers. If you need to support arbitrary numbers (floats, complex numbers, decimal.Decimal
instances) use the numbers.Number
abstract type:
from numbers import Number
new_list = [value for value in old_list if isinstance(value, Number)]
You can also give isintance()
a tuple of types to test against, if just need a a subset; for example:
new_list = [value for value in old_list if isinstance(value, (int, float))]
would filter on integers and floating point values.
[value for value in old_list if not isinstance(value, str)]
cover all bases?
Mar 31, 2016 at 8:38
not isinstance(value, str)
;)
Mar 31, 2016 at 8:42
Apart form the already mentioned comprehension, you can consider the built-in filter function:
new_list = filter(lambda x: isinstance(x, int), old_list)
filter
returns an iterator, not a list. Of course, in many situations an iterator may be superior to having a list, but if you do want a list, eg, so you can index into it or count it, then you can do list(filter(lambda x: isinstance(x, int), old_list))
.