Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 910
dassouki Avatar asked Aug 14 '09 13:08

dassouki


People also ask

How to print even numbers in a list in Python?

even_nos = [num for num in list1 if num % 2 == 0] print("Even numbers in the list: ", even_nos) Output: Even numbers in the list: [10, 4, 66] Using lambda expressions : list1 = [10, 21, 4, 45, 66, 93, 11] even_nos = list(filter(lambda x: (x % 2 == 0), list1)) print("Even numbers in the list: ", even_nos) Output:

What is a list in Python?

Python lists are one of the most versatile data types that allow us to work with multiple elements at once. For example, In Python, a list is created by placing elements inside square brackets [], separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.).

How to determine if an element is a number in Python?

To improve this, you can use operator.isNumberType to determine if an element is a number (see my other answer, to do this with filter instead of a list comprehension). import numbers [x for x in list_1 if isinstance (x, numbers.Number)] ok.. I don't know much of python 3k, so I have changed the example again. Hope it helps!

How to print a list of elements without using loops in Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively. a = [1, 2, 3, 4, 5]


1 Answers

List comprehensions.

list_2 = [num for num in list_1 if isinstance(num, (int,float))]
like image 71
Ants Aasma Avatar answered Sep 30 '22 05:09

Ants Aasma