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?
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:
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.).
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!
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]
List comprehensions.
list_2 = [num for num in list_1 if isinstance(num, (int,float))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With