Python count() method
The count()
method, list.count( obj )
counts and returns the number of times the specified element obj appears in the list.
If you want to know the number of elements in a list or string, you can use the count()
method. For strings, it returns the number of characters.
Related course: Complete Python Programming Course & Exercises
syntax
list.count( obj )
parameters
- obj: Specifies an element of the list to be counted
return value
- Returns the number of times this specified element obj appears in the list
count() example
Talk is cheap, so some count() examples are shown below. It counts the frequency of the parameter.
#coding=utf-8
lst = [5, "Zara", "Python", 2, 5, "Python", 5]
print("Count for 5:", lst.count(5))
print("Count for Python:", lst.count("Python"))
Example Run Results
Count for 5: 3
Count for Python: 2
example 2
The count function is used to count the number of times a character appears in a string or list. For example.
a = [1, 2, 3, 4, 5, 6, 2, 4, 2, 1, 5, 3, 2]
print(a.count(3))
# output 2
You can use the count() method on a string too:
str = "abcdefgsdafdfagda"
print(str.count("d", 2, 15))
# output 3
example 3
Another example is shown below:
ls = [1,2,3,5,4,5,5,5,5,"python"]
print(ls.count(5))
print(ls.count(0))
print(ls.count("python"))
This outputs
5
0
1
example 4
You can specify the start and end position.
str.count(sub, start= 0,end=len(string))
Count the number of times a character is in a string.
# coding=utf-8
string = 'Hello World ! Hello Python !'
print("string.count(sub) : ", string.count('H'))
print("string.count(sub, 1) : ", string.count('H', 1))
print("string.count(sub, 1, 100) : ", string.count('H', 1, 100))
Results:
string.count(sub) : 2
string.count(sub, 1) : 1
string.count(sub, 1, 100) : 1
The number of times an element is in the list
list = [10, 20, 30, 'Hello', 10, 20]
print("list.count('Hello') : ", list.count('Hello'))
print("list.count(10) : ", list.count(10))
Print results
list.count('Hello') : 1
list.count(10) : 2