count( ) is a built-in function of Python programming language. It is used to return the total number of occurrences of a specified element. It returns integers. count( ) function is used for List and Strings.
The count( ) method searches for the specified element in the string and the List.
The List count( ) returns the total count of how many times an item appeared in the List.
The String count( ) returns the total occurrences of a substring in the specified string.
This article will discuss how to use the count( ) method in String and List. The examples with code snippet and outputs are attached to help you understand better the count of elements.
Table of Contents
Python List count( ):
The list count( ) helps to count the object’s occurrences in the Python list. The elements in list will be counted. The List count function syntax is given as:
- Element: There is a single parameter, that is the element that will be counted.
The following example codes will help in proper understanding.
Example # 01: count( )
mylist1 = [2, 2, 3, 4, 6, 6, 6, 8,] count1= mylist1.count(6) print('The count of 6 is:', count1) mylist2 = ['Brazil', 'Canada', 'Mexico', 'Spain', 'Turkey', 'Canada'] count2= mylist2.count('Canada') print('The count of country Canada is: ', count2)
Example # 02: Tuple and List Element
mylist1 = [2, (2,8), (10,20), ['a','b'], ['cat', 'dog']] count1= mylist1.count((10,20)) print('The count is:', count1) count2= mylist1.count(['cat', 'dog']) print('The count is:', count2)
Python String count( ):
The String count( ) is used to count occurrence of substring appearances in string. It takes the parameters for starting and ending of the count of occurrence of substring. By default, counting starts from the start of the string till the end of the string.
The syntax for String count( ) is as follows:
string. count (char/substring, start, end)
- substring: the string that will be counted
- start: the starting index for the count. (optional)
- end: the ending index for the count. (optional)
The example codes are as follows:
Example # 01: Occurrence of Characters
mystring1 = "Welcome to Codeleaks!" char= "e" count1= mystring1.count(char) print('The count of e is:', count1)
Example # 02: Occurrence of Substrings
mystring1 = "Welcome to Codeleaks!" substring= "Codeleaks" count1= mystring1.count(substring) print('The count of Codeleaks is:', count1)
Example # 03: Elements with Optional Parameters
substring= "Codeleaks" count1= mystring1.count(substring, 0, 10) print('The count of Codeleaks is:', count1)
The article has explained many examples for the list count( ) and string count( ). You can use the built-in count method in your programming codes. I hope the concept is clear and understood in the article.