Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Print List ItemsE02. Sum List NumbersE03. Count List ElementsE

Problem No 3

Count List Elements

Easy

10 minute session

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.

Code editor
Loading editor…

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.

02:08 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.