Home » Python

How can I count the occurrences of a list item in Python?

Finding occurrences of a list item in Python: Here, we are going to learn how to count the occurrences of a list item in Python?
Submitted by Sapna Deraje Radhakrishna, on December 18, 2019

The python count() method counts the number of occurrences of an element in the list and returns it.

Syntax:

    list.count(x)

The count() method takes a single argument, x, whose count is to be found. The count() method returns the number of occurrences of an element in a list.

Example:

# an example of list.count() method in Python

# declaring a list
website_list = ['google.com','includehelp.com', 'linkedin.com', 'google.com']

# counting the occurrences  of 'google.com'
count = website_list.count('google.com')
print('google.com found',count,'times.')

# counting the occurrences  of 'linkedin.com'
count = website_list.count('linkedin.com')
print('linkedin.com found',count,'times.')

Output

google.com found 2 times.
linkedin.com found 1 times.

The count() method works on tuple as well

Example:

# an example of count() method with tuple in Python

# declaring a tuple
sample_tuple = ((1,3), (2,4), (4,6))

# conting occurrences  of (1,2)
count = sample_tuple.count((1,2))
print('(1,2) found',count,'times.')

# conting occurrences  of (1,3)
count = sample_tuple.count((1,3))
print('(1,3) found',count,'times.')

Output

(1,2) found 0 times.
(1,3) found 1 times.






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.