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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.