Count Occurrences

Count how many times element appears.

IntermediatePhase 4 - Level 2: Searching & Counting LogicExample 2 of 10
count-occurrences.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7x = int(input("Enter element to count: "))
8
9# Count occurrences
10count = arr.count(x)
11print(f"{x} appears {count} times")

Output

Enter array size: 6
Element 1: 5
Element 2: 3
Element 3: 5
Element 4: 7
Element 5: 5
Element 6: 2
Enter element to count: 5
5 appears 3 times

What's going on

Use count() method to count occurrences.

Key Concepts:

count(x) returns number of occurrences
Counts all matches
Simple and efficient