w3resource

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

Python Lambda: Exercise-49 with Solution

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

Sample Solution:

Python Code :

def count_occurrences(nums):
    result = dict(map(lambda el  : (el, list(nums).count(el)), nums))
    return result
nums = [3,4,5,8,0,3,8,5,0,3,1,5,2,3,4,2]
print("Original list:")
print(nums)
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}

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


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 Python skills with w3resource's quiz



Python: Tips of the Day

Splits values into two groups. If an element in filter is True, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group

Example:

def tips_bifurcate(lst, filter):
  return [
    [x for i, x in enumerate(lst) if filter[i] == True],
    [x for i, x in enumerate(lst) if filter[i] == False]
  ]

print(tips_bifurcate(['little', 'boo', 'peep', 'sat'], [True, True, False, True]))

Output:

[['little', 'boo', 'sat'], ['peep']]