Lesson guide
What this Python exercise practices
Count List Elements is a beginner practice lesson that focuses on loops, iteration, counters. It is designed to be solved in about 10 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Lists or strings
- Basic for loop syntax
Difficulty and time
- Level
- Beginner
- Estimated time
- 10 minutes
Related public exercises
Summary
Count how many times a value appears in a list using iteration.
Problem statement
Write a function count_occurrences(items, value) that returns the number of times value appears in the list items. Use a loop to compare each element to value and increment a counter when they are equal. Return 0 for empty lists. Handle any types that support equality comparison.
Task
Implement a function that iterates over a list and counts occurrences of a given value.
Examples
Count integers
Input
count_occurrences([1, 2, 1, 3], 1)
Output
2
Explanation
The value 1 appears twice in the list.
Input format
Two arguments: items (a list) and value (any type to compare).
Output format
An integer count of how many elements in items equal value.
Constraints
- items length may be 0 or more. - Use a loop and an integer counter. - Equality is checked with ==.
Samples
Sample input 0
count_occurrences(['a', 'b', 'a'], 'a')
Sample output 0
2
Explanation 0
There are two 'a' elements in the list.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.