What is the Python count()?

The Python count(), as the name implies, counts the occurrences of a given argument in a list or a string. It is used in the two ways shown below.

svg viewer

On the left,since “educative” has two instances of the letter ‘e’, count() returns 2. On the right, since “apples” occurs three times in the list, count() returns 3.


Examples


1. Counting occurrences of a string in a list:

​Since elephant occurs twice in mylist, the function returns 2.

mylist = ["elephant", "hippo", "panda", "elephant", "bear"]
print(mylist.count("elephant"))

2. Counting the number of a given substrings in a string:

Here, the string in substr is searched in the entire string mystr. sea occurs twice, hence why​ the function returns 2.

A slight modification to count from a string involves passing a starting and ending index. The string will be searched for the value within this range. The syntax for doing this is:

string.count(substr, start, end)
mystr = "sally sells sea shells on the sea shore"
substr = "sea"
print(mystr.count(substr))

3. Using start and end parameters:

Here, the substr is searched in mystr from position 0 to 8, only. Feel free to change these values, ​note change in result.

mystr = "educative is awesome, right?"
substr = 'a'
print(mystr.count(substr, 0, 8))
Copyright ©2024 Educative, Inc. All rights reserved