dassouki dassouki - 2 months ago 7
Python Question

Is there a way to output the numbers only from a python list?

Simple Question:

list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]


I want to create a
list_2
such that it only contains the numbers:

list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]


Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?

Answer

This should be the most efficent and shortest:

import operator
filter(operator.isNumberType, list_1)

Edit: this in python 3000:

import numbers
[x for x in list_1 if isinstance(x, numbers.Number)]