Tutorialspoint
Problem
Solution
Submissions

Occurrences of Each Element in a List

Certification: Basic Level Accuracy: 82.35% Submissions: 34 Points: 5

Write a Python program that counts how many times each element appears in a list and returns a dictionary.

Example 1
  • Input: lst = [1, 2, 2, 3, 3, 3]
  • Output: {1: 1, 2: 2, 3: 3}
  • Explanation:
    • Step 1: Create an empty dictionary to store the frequency of each element.
    • Step 2: Iterate through the list, counting occurrences of each element.
    • Step 3: Element 1 appears once, so add entry {1: 1}.
    • Step 4: Element 2 appears twice, so add entry {2: 2}.
    • Step 5: Element 3 appears three times, so add entry {3: 3}.
    • Step 6: Return the dictionary with all element frequencies.
Example 2
  • Input: lst = [4, 4, 4, 4]
  • Output: {4: 4}
  • Explanation:
    • Step 1: Create an empty dictionary to store the frequency of each element.
    • Step 2: Iterate through the list, counting occurrences of each element.
    • Step 3: Element 4 appears four times, so add entry {4: 4}.
    • Step 4: Return the dictionary with the element frequency.
Constraints
  • 1 ≤ len(lst) ≤ 10^3
  • -10^5 ≤ lst[i] ≤ 10^5
  • Time Complexity: O(n) where n is the length of the input list
  • Space Complexity: O(n) to store the frequency dictionary
ListHCL TechnologiesDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the Counter module from collections to count elements.
  • Convert the result to a dictionary.

Steps to solve by this approach:

 Step 1: Import the Counter class from the collections module.

 Step 2: Apply Counter to the input list to count occurrences of each element.
 Step 3: Convert the Counter object to a regular dictionary.
 Step 4: Return the dictionary mapping elements to their frequency counts.
 Step 5: Handle the case of an empty input list by returning an empty dictionary.

Submitted Code :