w3resource

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


49. Count Occurrences 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}

For more Practice: Solve these Related Problems:

  • Write a Python program to count the occurrences of each character in a string using lambda.
  • Write a Python program to count the occurrences of each word in a list using lambda.
  • Write a Python program to count the frequency of even and odd numbers separately in a list using lambda.
  • Write a Python program to count the occurrences of items in a list and return a dictionary sorted by frequency using lambda.

Go to:


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.

Python Code Editor:

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

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.