Python count() Function

Overview

The Python count function is a tool that helps you find how often a specific element appears in a sequence whether its a string or a list.

When using the count() method for strings it tells you how times a particular substring shows up in the given string. This can be helpful for tasks like tallying character frequencies or counting spaces. For instance you could use it to figure out the number of vowels in a word or to see how many spaces are in a sentence.

As for the count() method with lists it calculates how times a specific element is present within the list and gives you that count. This feature comes in handy when you need to track occurrences of words in sentences or determine the frequency of specific numbers in lists of integers.

Syntax of the count function

In Python the count() function tallies up instances of characters or substrings within strings, with this syntax —

string.count(substring, start, end)

Here "string" represents the string where we want to find occurrences.

The substring refers to the character. Substring we want to tally within the provided string. The start is a parameter that indicates the initial index of the search starting from the beginning of the string by default. Similarly the end is also a parameter that denotes the concluding index of the search defaulting to searching until the end of the string. The count() function is case sensitive distinguishing between uppercase and lowercase characters. It provides an integer value representing how times a specified character or substring occurs, in the given string.

For instance if we have a string "Hello, World!". Wish to count how many times 'l' appears in it we can do so using the count() function as shown below.

count = "Hello, World!”.count('l')
print(count)

This code would result in 3 since 'l' appears three times in the string.

Example of counting occurrences in a list

To count how often elements occur in a list you can employ the count() method. For example ponder over this list of numbers; [1, 2, 3 4, 2 2].
To determine how times the number 2 appears in this list you would simply apply the count() method directly to the list —

numbers = [1, 2, 3, 4, 2, 2]
count = numbers.count(2)
print(count)

The result will be 3 as the number 2 shows up three times in the list.

Counting Elements in Different Data Structures

Counting elements within data structures plays a key role in programming. The approach to counting elements can differ based on the data structure being used.

Counting elements in a string

For counting elements within a string you can utilize either the count() method or the collections.Counter() function. For instance —

from collections import Counter
string = "Hello World"
count = string.count('l')
counter = Counter(string)
print(count)  # Output: 3
print(counter['l'])  # Output: 3

Counting elements in a tuple

When it comes to counting elements within a tuple you can make use of the count() method.

tuple_elements = (1, 2, 3, 2, 2)
count = tuple_elements.count(2)
print(count)  # Output: 3

Counting elements in a dictionary

To tally the items in a dictionary you usually loop through the values and manually keep track of occurrences.

fruits = {'apple': 3, 'banana': 2, 'cherry': 5}
count = list(fruits.values()).count(2)
print(count)  # Output: 1

Using Keyword Arguments in the count function

The count function allows you to use keyword arguments like start and end to define the counting range.

string = "Hello World"
count = string.count('o', start=3)  # Counts 'o' starting from index 3
print(count)  # Output: 2

Handling Negative Values as Counts

The count() method does not support values for counts. It will only provide counts of substring occurrences.

Advanced Usage

Counting occurrences of substring in a string

To count occurrences of a substring in a string:

string = "I love apples and apples are delicious"
substring = "apple"
occurrences = string.count(substring)
print(occurrences)  # Output: 2

Using regular expressions with the count function

To tally how times a substring appears in a string.

import re
string = "Hello World! Hello Python!"
pattern = re.compile(r"Hello")
matches = pattern.findall(string)
count = len(matches)
print(count)  # Output: 2

Working with Lists and Tuples

Here is a Python snippet that demonstrates how to use the count method with both lists and tuples.

numbers = [1, 2, 3, 2, 2]
count = numbers.count(2)
print(count)  # Output: 3

tuple_elements = (1, 2, 3, 2, 2)
count = tuple_elements.count(2)
print(count)  # Output: 3

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate