Q.Write a program to find the number of times an element occurs in the list.
Frequency counting is the accumulator pattern applied to a condition: walk the list once, add 1 to a counter each time the element matches — Python's built-in list.count() does exactly this in one call.
The idea. "How many times does x occur?" is a single-pass scan: compare every element with x and count the matches. Writing the loop yourself shows the logic; count() is the idiomatic shortcut and a good cross-check.
Program:
myList = eval(input("Enter the list: "))
element = eval(input("Enter the element to count: "))
count = 0
for item in myList:
if item == element:
count = count + 1
print(element, "occurs", count, "time(s) in the list")
print("Cross-check with count():", myList.count(element))
Key lines: eval(input(...)) lets the user type a whole list literal like [10, 20, 10] (the NCERT-style input idiom); the for loop visits each element; the if adds 1 only on a match.
Expected output (sample run):
Enter the list: [10, 20, 10, 30, 10, 40]
Enter the element to count: 10
10 occurs 3 time(s) in the list
Cross-check with count(): 3
Trace for the sample:
| item | item == 10? | count |
|---|---|---|
| 10 | Yes | 1 |
| 20 | No | 1 |
| 10 | Yes | 2 |
| 30 | No | 2 |
| 10 | Yes | 3 |
| 40 | No | 3 |
If the element is absent (e.g. 99), the counter simply stays 0 and the program honestly reports 0 occurrences — no special case needed.
In exam answers, showing the manual loop earns the logic marks; mentioning myList.count(element) shows you know the library. Both run in O(n) time — every element must be examined once.
The program scans the list once, incrementing count whenever item == element, and reports the total; for the sample list [10, 20, 10, 30, 10, 40] with element 10, the output is "10 occurs 3 time(s) in the list".
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.