Frequency of Elements

Write a Python function to count the frequency of elements in a list. The function should return a dictionary where the keys are the elements in the list and the values are their corresponding frequencies.

Example 1:

Input: [1,2,2,3,3,3,4,4,4,4] 
Output: {1:1, 2:2, 3:3, 4:4}

Example 2:

Input: ['apple', 'banana', 'apple', 'cherry', 'cherry', 'cherry'] 
Output: {'apple': 2, 'banana': 1, 'cherry': 3}

Use a dictionary to keep track of the frequencies.

def count_elements(lst):
    return {i: lst.count(i) for i in lst}

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!