The count function is an inbuilt function in Python that counts the occurrence of a specific value in a string or list. This function is straightforward and efficient, making it a valuable tool in a programmer’s toolkit. This article explores how to use the count() function, its syntax, and some practical examples to illustrate its functionality.
Introduction
Python’s count() function is a powerful tool for strings and lists. It counts the occurrences of a specified value within the string or list. This function is simple yet quite useful in analyzing data and finding the frequency of specific elements or characters.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Syntax of count() function in Python
Here is the syntax of the count function.
string.count(substring/character, start=, end=)
Parameters of count() function in Python
The count() function accepts three parameters. Let’s discuss each parameter one by one.
substring/character: It is to be searched in the string.
start(optional): The starting index from where the search begins. The default value of this parameter is zero. This parameter is also optional.
end (optional for strings): This ending index is where the search ends. The default is the length of the string. It is an optional parameter.
Return Value of count() function in Python
The count() function returns the integer type.
Example of count() function in Python
The following program demonstrates the count() function in Python language.
Program
str="Hello Neeraj Kumar"
counts = str.count('r')
print("Occurrence of r in string", counts)
Output
Occurrence of r in string 2
Using count() with the start and end parameters
The following program demonstrates the count() function in Python. It explains all about the count() function in Python.
Program
<strong> </strong>text = "Python Programming language. This language anyone can learn. Python is also a versatile programming language."
count = text.count("Python", 0, 20)
print(count)
Output
1
Example of count() function with Lists
The following program demonstrates the count() function, equally useful when applied to the lists. Let’s discuss the lists.
Example 3: Count method with Substring in a Given Binary String
Let’s use count() on strings to find the occurrence of any of its substrings (more than one character) in that string.
Program
string1 = '0100011111010101111011101111100000111111010101010101010010'
occurrenceOf01 = string1.count('01')
print('Occurrence of "01" in string1: ', occurrenceOf01)
Output
Occurrence of “01” in string1: 16
Example 4: Using Start Position Parameters
The count() on strings searches for the occurrence of a substring(more than one character ) in the string, using only the one optional parameter ‘start’ to search the substring at the specified start position.
Program
string1 = 'ab bc ba ab bc cb xz qs ab hj ab ja ab xz rd md xz wr xz'
occurenceOfSubString = string1.count('ab', 11)
print('Occurrence of a substring in string1: ', occurenceOfSubString)
Output
Occurrence of a substring in string1: 3
Example 5: Using End Position Parameters
The count() function on strings is used to find the occurrence of any of its substrings (more than one character) in that string by passing only one optional parameter ‘end’ to specify the end position until we find the substring here.
Program
string1 = 'ab bc ba ab bc cb xz qs ab hj ab ja ab rm cd xz pt lr'
occurenceOfSubString = string1.count('ab', None, 15)
print('Occurrence of substring in string1: ', occurenceOfSubString)
Output
Occurrence of substring in string1: 2
Example 6: Using both Optional Parameters
In this case, the count() function strings to find the occurrence of any of its characters in that string by passing some additional optional parameters start & end as discussed earlier
Program
str= "Neeraj Kumar"
occur = str.count('r',0, 5)
print("Occurrence of r from 3rd to 14th index in string1:", occur)
Output
Occurrence of r from 3rd to 14th index in string1: 1
The count() function introduced in Python is one of the easiest to use and most effective in returning the number of times an element occurs in a sequence like a list, string or tuple. Based on the sequence, it scans it and gives the total count of how many times the element appeared. This function is particularly helpful for jobs where the frequency of counting is high for example, text mining or data analysis. Its syntax is quite simple and can be added into simple and complex Python projects with ease. However, it fails to change the original sequence and must be used with one element at a time it cannot be applied at bulk. Want to learn more about Python programming? Consider the Accelerator Program in Business Analytics and Data Science offered by Hero Vired in collaboration with edX and Harvard University.
FAQs
What does the count() function do in Python?
Python's count() function counts the number of occurrences of a specified element in a sequence (such as a list, tuple, or string). It returns an integer representing the number of times the element appears in the sequence.
Does count() work with any data type in lists or tuples?
Yes, the count() works with any data type in lists or tuples. It can count occurrences of integers, strings, floats, booleans, and even complex objects (as long as they are comparable).
What does the count() function return if the elements are not found?
If the specified element is not found in the sequence, the count() function returns 0.
How can I limit the search range using the strings' count() function?
You can provide optional start and end parameters for strings to limit the range in which the count() function searches for the substring. For example, string.count(substring, start, end) will only count occurrences between the indices start and end.
Does the count() function raise any errors?
No, the count() function generally does not raise errors. If the element or substring is not found, It simply returns 0. It will only raise an error if you call it on an inappropriate object type (e.g. typing to use count() on a number).
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.