To find all the numerical values in a list in python, you can use various approaches depending on the structure and content of your list . Here’s a detailed explanation using different methods:
METHOD 1: USNG LIST COMPREHENSION
List comprehension is a concise and pythonic way to iterate over a list and filter out elements based on a condition.
my-list = [10,’hello’, 20.5, ‘123’, true, 45, ‘world’]
numerical-values = [x for x in my-list if is instance (x, (int, float ))]
print(numerical-values)
EXPLANATION: ‘is instance(x, (int , float))’ check if each element ‘x’ in ‘my-list’ is either an ‘int’ or a ‘float’.
. ‘ [x for x in my-list if is instance (x, (int, float))]’ create a new list (‘numerical-values’) containing only those element ‘my-list’ that are numerical.
METHOD 2: USING ‘FILTER()’ WITH ‘LAMBDA’ FUNCTION
You can also use the ‘filter()’ function in combination with ‘lambda’ function to achieve the same result.
my-list = [10, ‘hello’, 20.5, ‘123’, true, 45, ‘world’]
numerical-values = list(filter(lambda x: is instance(x, (int, float)), my-list))
EXPLANATION: ‘Lambda x: is instance(x,(int, float))’ defines an anonymous function that check if ‘x’ is either an ‘int’ or a ‘float’.
METHOD 3: USING ‘ISDIGIT()’ FOR STRING
If you list contains strings that represent number (like’123′) , you can use the ‘isdigit()’ method to check if a string.
my-list = [10, ‘hello’, 20.5, ‘123’, true, 45, ‘world’]
numerical-values = [x for x in my-list if is instance(x,(int, float))
print(numerical-values)
EXPLANATION: ‘x. isdigit()’ check if ‘x’ (a string) consists only of digits.
Mixed types: These methods handle lists containing a mix of types (integers, float, string, etc.) by filtering out only those that are considered numerical (ints and floats).
Difference between np.asarray() and np.array()
my-list = [1, 'apple', 3.14, 'orange', 5, 7.5, 'banana'] numerical-values = find-numerical-value(my-list) print("numerical values in the list:",numerical-values)
OUTPUT:
numerical values in the list [1, 3.14, 5, 7.5]