w3resource

Python: Count the occurrences of the items in a given list using lambda


Write a Python program to count the occurrences of items in a given list using lambda.

Sample Solution:

Python Code :

# Define a function 'count_occurrences' that counts occurrences of each item in a list
def count_occurrences(nums):
    # Convert 'nums' to a list and map each element to a tuple containing the element and its count in 'nums'
    # Use the 'dict' function to convert the mapped result to a dictionary
    result = dict(map(lambda el: (el, list(nums).count(el)), nums))
    
    # Return the dictionary containing the count of occurrences of each item
    return result

# Create a list 'nums' containing integer values
nums = [3, 4, 5, 8, 0, 3, 8, 5, 0, 3, 1, 5, 2, 3, 4, 2]

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

# Count the occurrences of items in the list using the 'count_occurrences' function and print the result
print("\nCount the occurrences of the items in the said list:")
print(count_occurrences(nums)) 

Sample Output:

Original list:
[3, 4, 5, 8, 0, 3, 8, 5, 0, 3, 1, 5, 2, 3, 4, 2]

Count the occurrences of the items in the said list:
{3: 4, 4: 2, 5: 3, 8: 2, 0: 2, 1: 1, 2: 2}

Python Code Editor:

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

Previous: Write a Python program to sort a given list of strings(numbers) numerically using lambda.

Next: Write a Python program to remove specific words from a given list 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.