Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 7

Count occurrences of a value in a list

Easy

6 minute session

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.

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.

07:44 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.