Python List count() Method (with Examples)

Python List count() Method: In this tutorial, we will learn about the count() method of the list class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 20, 2023

Python List count() Method

The count() is an inbuilt method of the list class that 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

The following is the syntax of count() method:

list_name.count(element)

Parameter(s):

The following are the 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: Use of List count() Method

# 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: Use of List count() Method

# 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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.