count() to get number of matching items

count() takes one argument.

returns number of matching value.
my_list=['a','b','c','b','a','d']
print("Number of times a appears : ", my_list.count('a'))
print("Number of times b appears : ", my_list.count('b'))
print("Number of times c appears : ", my_list.count('c'))
Output
Number of times a appears :  2
Number of times b appears :  2
Number of times c appears :  1

Example: Counting Items That Don’t Exist

my_list = ['x', 'y', 'z']
print("Count of 'a':", my_list.count('a'))  # should print 0, because 'a' is not in list
  • This shows that `count()` returns 0 for missing elements, not an error.

Example: Custom Objects with __eq__

class Person:
    def __init__(self, name):
        self.name = name
    def __eq__(self, other):
        return isinstance(other, Person) and self.name == other.name

p1 = Person("Alice")
p2 = Person("Bob")
p3 = Person("Alice")
lst = [p1, p2, p3]

print("Count of Person('Alice'):", lst.count(Person("Alice")))  # 2
  • Demonstrates how equality definition in a class affects counting.

Example: Count Multiple Targets Efficiently

from collections import Counter

my_list = ['a', 'b', 'b', 'c', 'a', 'd', 'b']
cnt = Counter(my_list)
print("Count of 'a':", cnt['a'])
print("Count of 'b':", cnt['b'])
print("Top two frequent items:", cnt.most_common(2))
  • Using `collections.Counter` avoids scanning list multiple times for different items.

Example: Real‑World Use Case (Text Processing)

text = "apple orange apple banana apple fruit"
words = text.split()
print("Number of 'apple':", words.count('apple'))
  • Useful for simple word frequency in small texts, e.g. for surveys or parsing logs.
All list methods Questions with solutions on List pop() to remove item based on position
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer