w3resource

Python: Count float number in a given mixed list using lambda

Python Lambda: Exercise-32 with Solution

Write a Python program to count float values in a mixed list using lambda.

Sample Solution:

Python Code :

# Define a function 'count_integer' that takes a list 'list1' as input
def count_integer(list1):
    # Create a boolean list 'ert' indicating whether each element in 'list1' is a float or not
    ert = list(map(lambda i: isinstance(i, float), list1)) 
    
    # Count the number of 'True' values (floats) in the boolean list 'ert'
    result = len([e for e in ert if e])
    
    # Return the count of floats in the input list
    return result

# Create a mixed list containing integers, strings, and floats
list1 = [1, 'abcd', 3.12, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]

# Print the original mixed list 'list1'
print("Original list:")
print(list1)

# Print the number of floats in the mixed list using the 'count_integer' function
print("\nNumber of floats in the said mixed list:")
print(count_integer(list1)) 

Sample Output:

Original list:
[1, 'abcd', 3.12, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]

Number of floats in the said mixed list:
3

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to extract specified size of strings from a give list of string values using lambda.
Next: Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.