Problem No 7
Count occurrences of a value in a list
Easy≈ 6 minute session
Lesson guide
What this Python exercise practices
Count occurrences of a value in a list is a beginner practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 6 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Beginner
- Estimated time
- 6 minutes
Practice path
Summary
Count how many times a given value appears in a list.
Problem statement
Given a list and a target value, return the number of times the target occurs in the list. The list may contain elements of any type (ints, strings, None, etc.). The comparison should be the standard equality comparison (==).
Task
Write a function that returns the number of times a target value appears in a list.
Examples
Basic example
Input
count_occurrences([1, 2, 1, 3, 1], 1)
Output
3
Explanation
The value 1 appears three times in the list.
Input format
A list (first argument) and a value to count (second argument).
Output format
An integer representing how many times the value appears in the list.
Constraints
The list length can be from 0 up to typical memory limits. Aim for O(n) time.
Samples
Sample input 0
count_occurrences(['a', 'b', 'a'], 'a')
Sample output 0
2
Explanation 0
The string 'a' appears twice.
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.