Home »
Python
Python List count() Method with Example
Python List count() Method: Here, we are going to learn how to count the frequency of a specified element in Python?
Submitted by IncludeHelp, on December 03, 2019
List count() Method
count() method is used to count the total number of the specified element, the method is called with this list (original list) and an element is passed as an argument and it returns the frequency of the given element.
Syntax:
list_name.count(element)
Parameter(s):
- element – It represents an element whose frequency to be counted.
Return value:
The return type of this method is <class 'int'>, it returns an integer (zero or greater than 0) value that is the frequency of the given element.
Example 1:
# Python List count() Method with Example
# declaring the list
cars = ["Porsche", "Audi", "Lexus", "Porsche", "Audi"]
# printing the list
print("cars: ", cars)
# counting the frequency of "Porsche"
cnt = cars.count("Porsche")
print("Porsche's frequency is:", cnt)
# counting the frequency of "Lexus"
cnt = cars.count("Lexus")
print("Lexus's frequency is:", cnt)
# counting the frequency of "BMW"
cnt = cars.count("BMW")
print("BMW's frequency is:", cnt)
Output
cars: ['Porsche', 'Audi', 'Lexus', 'Porsche', 'Audi']
Porsche's frequency is: 2
Lexus's frequency is: 1
BMW's frequency is: 0
Example 2:
# Python List count() Method with Example
# declaring the lists
x = ["ABC", "XYZ", "PQR","ABC", "XYZ", "PQR"]
y = ["PQR", "MNO", "YXZ", "YXZ"]
z = ["123", "456", "789"]
# printing the frequency of given element
print('x.count("ABC"):', x.count("ABC"))
print('y.count("YXZ"):', y.count("YXZ"))
print('z.count("789"):', z.count("789"))
Output
x.count("ABC"): 2
y.count("YXZ"): 2
z.count("789"): 1
TOP Interview Coding Problems/Challenges