Count Function in Python – Understanding with Examples

Updated on October 16, 2024

Article Outline

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.

*Image
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.

Program

<strong> </strong>numbers = [1, 2, 3, 4, 2, 3, 2, 4, 5] count = numbers.count(2) print(count)

Output

3

Counting Non-Numeric Elements in Lists

We can also use the count() function to count non-numeric elements, such as strings in a lists.

 

Program

fruits = ["apple", "banana", "apple", "orange", "banana", "voldemort", "ronaldo", "computer system"] count = fruits.count("apple") print(count)

Output

2

 

Also Read: List in Python

Application of count() function in Python

 

  • The count() function can find the white spaces in a given string.
  • The count() function can determine the frequency of any character in a given string.
  • The count() function can also be used to determine the count of a given word in a string.

More Examples

Example 1: Using the Count Method with a Substring

 

In this section, we use the count() function that strings to find the occurrences of any of its substrings (more than one character) in that string.

 

Program

string1 = 'abcdabcdabcdbcdefghqwert' occurrenceOfSubstring = string1.count('abcd') print("Occurrence of 'abcd' in string1: ", occurrenceOfSubstring)

Output

Occurrence of ‘abcd’ in string1:  3

 

Example 2: Count method with Character in a Given Binary String

 

The count() on a string is used to find the occurrence of its characters in that binary string.

 

Program

string1 = '0100011111010101111011101111100000111111010101011110000100' occurrenceOf0 = string1.count('0') print('Occurrence of 0 in string1: ', occurrenceOf0)

Output

Occurrence of 0 in string1:  2

 

Also Read: Top Python Interview Questions and Answers

 

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

 

Also Read: Top 50 Python Programming Examples

Conclusion

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
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.
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).
If the specified element is not found in the sequence, the count() function returns 0.
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.
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).

Updated on October 16, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
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.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved