Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Occurrences

Count occurrences of a chosen integer in a Python list. Students use list.count and distinguish zero matches, repeated entries, and a single combined result.

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

In this one

  • Query an occurrence count
  • Handle absent targets
  • Preserve repeated entries

How it works

  1. 1

    Collect the list and target.

  2. 2

    Call arr.count(x).

  3. 3

    Print the returned number of matching entries.

Edge cases

What if x is absent?

What if x is absent?

count returns zero.

Does the list need sorting?

Does the list need sorting?

No. Equal entries can occur anywhere.

What's going on

arr.count(x) counts every element equal to x. It is a frequency query, not an index lookup.

For a list containing 2, 2, and 5, searching for two returns two. An absent value returns zero instead of raising an error. The method scans the stored entries and leaves their contents and order unchanged.

What if x is absent? count returns zero.

Does the list need sorting? No. Equal entries can occur anywhere.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does count return?

Pick an answer to check it.

Question 2

What if x is absent?

Pick an answer to check it.

Questions people ask

What if x is absent?

count returns zero.

Does the list need sorting?

No. Equal entries can occur anywhere.

What does count return?

The number of matches.