Counting Occurrences in Python Lists

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, it is often necessary to count the number of occurrences of a specific value in a list. This can be useful in a variety of situations, such as analyzing data or processing user input. In this challenge, you will be tasked with writing a function that counts the number of occurrences of a given value in a list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") subgraph Lab Skills python/comments -.-> lab-13609{{"`Counting Occurrences in Python Lists`"}} python/lists -.-> lab-13609{{"`Counting Occurrences in Python Lists`"}} python/tuples -.-> lab-13609{{"`Counting Occurrences in Python Lists`"}} python/function_definition -.-> lab-13609{{"`Counting Occurrences in Python Lists`"}} end

Count Occurrences

Write a function count_occurrences(lst, val) that takes a list lst and a value val as arguments and returns the number of occurrences of val in lst. Your function should use the built-in list.count() method to count the number of occurrences.

def count_occurrences(lst, val):
  return lst.count(val)
count_occurrences([1, 1, 2, 1, 2, 3], 1) ## 3

Summary

In this challenge, you learned how to count the number of occurrences of a value in a list using the list.count() method. This is a useful technique that can be applied in a variety of programming tasks.

Other Python Tutorials you may like