Learn Count Function in Python with Examples | Simplilearn (2024)

Python is a high-level, interpreted programming language that has gained immense popularity in data science, machine learning, and web development. One of Python's most useful built-in functions is the count() function, which allows you to count the number of occurrences of a particular element in a python list count or a tuple. In this article, we will learn how to use the count function in Python and explore its practical applications.

Python's count() function is a built-in function that allows you to count the number of times an element appears in a list or tuple. This function can be handy when dealing with large datasets or when you need to perform calculations based on the frequency of certain elements.

Want a Top Software Development Job? Start Here!

Full Stack Development-MEANExplore Program

Learn Count Function in Python with Examples | Simplilearn (1)

How to Use Count Function in Python?

To use the count() function in Python, you must first have a python list count list or a tuple that you want to count elements. The syntax for using the count() function is as follows:

Learn Count Function in Python with Examples | Simplilearn (2)

Explanation:

  • The count() function is called on the list my_list.
  • The argument passed to the count() function is element 3.
  • The function returns the number of times three appears in the list my_list, which is 2.
  • The result is printed to the console.

There is another example:

Learn Count Function in Python with Examples | Simplilearn (3)

Output:

2

Explanation:

  • The count() function is called on the tuple my_tuple.
  • The argument passed to the count() function is element 1.
  • The function returns the number of times one appears in the tuple my_tuple, which is 2.
  • The result is printed to the console.

Thecount()method is one of the inbuilt functions in Python. As the name implies, it returns the number of times a specified value appears in a string or a list.

In real-time, we deal with statistical functions and financial functions where the number of arguments contains numbers and the number of cells contains numbers too. Hence, the count method helps us immensely.

This method is also used to count numbers in the given set of arrays.

There are two types of methods for ‘count’ in Python. They are as follows:

  1. String count() method
  2. List count() method

PYTHON String Count() Method:

The count () in Python is used to count the number of times a substring occurs in each string. A single parameter (substring value) is quite enough for execution, optionally the other two values are also available.

Syntax:

string.count(value, start, end)

or

string.count(value)

Parameter values:

Value: This is the substring whose count in Python is to be found. This can be a single character or a substring, which needs to be searched for in the given string.

Start (Optional): This should be an integer, which is the index value to start the search in the given string. By default, it starts from 0, when the value is not given.

End (Optional): This should be an integer, which is the index value to end the search. By default, it is the end of the string. When the end value is not given, it will find values until the end of the string or list.

The count in the Python method returns a number as a return value. The integer value is the return value. When the count in Python returns 0, then it means that the value is not found in the list or string.

Want a Top Software Development Job? Start Here!

Full Stack Development-MEANExplore Program

Learn Count Function in Python with Examples | Simplilearn (4)

Example 1:

Code 1:

# this line for declaring a variable and its value

myText = "I love Paris, Paris is my favorite tourist destination"

# this line for calling the count method

numofCounts = myText.count("Paris")

# this line for print output

print("{} number of times".format(numofCounts)) # format is the inbuilt

function to use join the values.

Output:

2 number of times

Learn Count Function in Python with Examples | Simplilearn (5)

In the above example, the count method will search for the word “Paris'' in myText. It will return 2 as an integer value since the word Paris occurs two times in the string. The variable ‘numofCounts’ will get the return value and display the result.

Example 2:

Code 2:

# this line for declaring the variable and its value

myText = "I love Paris, Paris is my favorite tourist destination"

# this line for calling the count method with start and end value

numofCounts = myText.count("Paris",8,20) # 8 is start value , 20 is end value

# this line for print output

print("{} number of times".format(numofCounts))

# format is the inbuilt function to use join the values.

Output

1 number of times

Learn Count Function in Python with Examples | Simplilearn (6)

In the above example, the same count method searches for the word “Paris” from the specified index value. Here, the count method has two more parameters. The starting search point is the 8th index, and it ends the search at the 20th index value of myText string (“aris, Paris is”). So, it returns only 1 time.

Want a Top Software Development Job? Start Here!

Full Stack Development-MEANExplore Program

Learn Count Function in Python with Examples | Simplilearn (7)

PYTHON List Count() Method:

The count() method in Python returns the number of elements that appear in the specified list. This method takes a single argument as input. It iterates the list and counts the number of instances that match it.

Syntax:

list.count(value)

Parameters:

Value—The value to be counted in Python. It can be of any type (String, number, list, etc.)

Example 1:

Code 3:

# this line for declare variable and its value

cities= ["Paris","London","New York"]

# this line for calling count method

numofCount =cities.count("Paris") # this is for test data Paris already Exist

numofTestCount = cities.count("Rome") # this is for test data Rome not exist in list

# this line for print output

print("{} number of times".format(numofCount)) # one because paris exist in List

print("{} number of times".format(numofTestCount)) # zero because Rome not exist in List

Output

1 number of times

0 number of times

Learn Count Function in Python with Examples | Simplilearn (8)

Note that in the above example, the print numofTestCount output is 0, as it received an invalid or non-existent parameter.

Example 2:

Count from even number list:

Code 4:

# this line for declaring the variable and its value

evennumbers= [2,4,6,8,10,12,14,16,18,20,22]

# this line for calling the count method

numofEvens = evennumbers.count(4)

print("{} number of times".format(numofEvens)) # format is the inbuilt function to use join the values.

Output

1 number of times

Learn Count Function in Python with Examples | Simplilearn (9)

You might have noticed that the output of print numofEvens was 1, though 2 appears at 12 and 20 in the list. It is because the list only counts the element which matches the data type and the value of the parameter passed.

Example 3:

Count from tuple

Code 5:

# this line for declare variable and its value

cities = [('Paris',1),('London',2),('Rome',3)] # here we passing Tuple values

numofCounts = cities.count(('London',2))# here we pass only one tuble value . if we pass more tuple values we will face Type Error

print("{} number of times".format(numofCounts)) # format is the in-build function to use join the values.

Output

1 number of times

Learn Count Function in Python with Examples | Simplilearn (10)

In the above example, cities denote the list variable that holds a few tuple values. We can find the tuple value with the help of the count method in the list. The numofCounts variable displays 1 since the value was found one time.

When we deal with the list count method, the error possibility in the count method is TypeError. When over 1 parameter is passed, it throws TypeError.

Want a Top Software Development Job? Start Here!

Full Stack Development-MEANExplore Program

Learn Count Function in Python with Examples | Simplilearn (11)

Practical Applications

The count() function can be used with lists and tuples, which is very versatile. Here are some practical applications of the count() function:

  • You are counting the number of occurrences of a specific word or character in a string. If you have a large string and want to know how many times a particular word or character appears, you can use the count() function. Convert the string to a list or a tuple, then call the count() function on it with the element you want to count.
  • Checking for duplicates in a list or a tuple. If you have a large list or tuple and want to check for any copies, you can use the count() function. Loop through the elements in the list or tuple and call the count() function on each one. If the count is greater than 1, you know the element is duplicated.
  • Finding the frequency of specific elements in a dataset. If you have a large dataset and want to know how many times a part appears, you can use the count() function. Convert the dataset to a list or a tuple, then call the count() function on it with the element you want to count.
  • Determining the number of times a certain event occurs in a log file. If you have a log file and need to know how often a certain event requires information about the frequency or occurrence of a specific event or element, you can use the count() function. Loop through the lines in the log file, and call the count() function on each line with the event you want to count.

There are some more practical applications of the count() function in Python:

  • Finding the most common element in a list or a tuple:

Learn Count Function in Python with Examples | Simplilearn (12)

Output:

Learn Count Function in Python with Examples | Simplilearn (13)

Explanation:

  • The max() function is used to find the element with the highest count in the list my_list.
  • The key argument is set to my_list.count to count the number of occurrences of each element in the list.
  • The result is printed to the console.

Choose The Right Software Development Program

This table compares various courses offered by Simplilearn, based on several key features and details. The table provides an overview of the courses' duration, skills you will learn, additional benefits, among other important factors, to help learners make an informed decision about which course best suits their needs.

Program NameAutomation Testing Masters ProgramFull Stack Developer - MEAN StackCaltech Coding Bootcamp
GeoAllAllUS
UniversitySimplilearnSimplilearnCaltech
Course Duration11 Months11 Months6 Months
Coding Experience RequiredBasic KnowledgeBasic KnowledgeBasic Knowledge
Skills You Will LearnJava, AWS, API Testing, TDD, etc.HTML, CSS, Express.js, API Testing, etc.Java, JavaScript, Angular, MongoDB, etc.
Additional BenefitsStructured Guidance
Learn From Experts
Hands-on Training
Blended Learning Program
Learn 20+ Tools and Skills
Industry Aligned Projects
Caltech Campus Connect
Career Services
17 CEU Credits
Cost$$$$$$$$
Explore ProgramExplore ProgramExplore Program

Conclusion:

Count() is a Python built-in function that returns the number of times an object appears in a list. The count() method is one of Python's built-in functions. It returns the number of times a given value occurs in a string or a list, as the name implies. In real-time, we deal with statistical functions and financial functions where the number of arguments containing numbers, or the number of cells containing a number, will benefit from the count process. This approach can also be used to count the number of elements in an array.

The basics of Python and how to apply it to real-world applications are covered in this Python training course. Data operations in Python, strings, conditional statements, error handling, shell scripting, web scraping, and the frequently used Python web system ‘Django’ are covered in the modules. Lesson-end tasks and assignments make up the curriculum, among other interesting learning methods. If you are further interested in enhancing your development skills, then we would recommend you check our Post Graduate Program in Full Stack Web Development in collaboration with Caltech CTME.

Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on the same at the earliest.

As a seasoned enthusiast in Python programming and its diverse applications, I'll delve into the concepts presented in the article, highlighting key points and providing additional insights.

Python's count() Function Overview:

1. Introduction to Python's count() Function:

  • Python is a high-level, interpreted programming language widely used in data science, machine learning, and web development.
  • The count() function is a built-in function in Python, particularly useful for counting occurrences in lists or tuples.

2. How to Use the count() Function in Python:

  • The syntax: list_or_tuple.count(element)
  • Demonstrated examples using both lists and tuples.

    # Example with a list
    my_list = [1, 3, 2, 3, 4, 3, 5]
    result = my_list.count(3)
    print(result)  # Output: 3

3. String count() Method:

  • Syntax: string.count(value, start, end)
  • Examples illustrating the use of the method on strings.

    # Example with a string
    my_text = "I love Paris, Paris is my favorite tourist destination"
    count_paris = my_text.count("Paris")
    print(count_paris)  # Output: 2

4. List count() Method:

  • Syntax: list.count(value)
  • Examples demonstrating the application of the method on lists.

    # Example with a list
    cities = ["Paris", "London", "New York"]
    count_paris = cities.count("Paris")
    print(count_paris)  # Output: 1

5. Practical Applications:

  • Counting occurrences of a word or character in a string.
  • Checking for duplicates in a list or tuple.
  • Finding the frequency of specific elements in a dataset.
  • Determining the number of times a certain event occurs in a log file.

6. Additional Applications:

  • Finding the most common element in a list or tuple.

    # Example finding the most common element
    max_occurrence = max(my_list, key=my_list.count)
    print(max_occurrence)

Conclusion:

In conclusion, the count() function is a versatile tool in Python, applicable to various scenarios, from simple list manipulations to complex data analysis tasks. Its usage spans different data structures and is invaluable in scenarios where counting occurrences is essential. The provided examples and explanations aim to equip readers with a solid understanding of the count() function's capabilities and its diverse applications in Python programming.

Learn Count Function in Python with Examples | Simplilearn (2024)
Top Articles
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 6224

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.