Python list.count(): Count Element Occurrences

The list.count() method returns the number of times a specified value appears in a list. If the item is not present, it returns 0 without raising an error.

Parent Guide: To learn about creating, modifying, and iterating over Python lists, visit the Python Lists Overview.

Syntax & Parameters 🔝

The count() method is invoked directly on a list instance:

list.count(value)
Parameter Type Required? Description
value Any Yes The target element to search for and count. The method checks for equality (item == value) against every element in the list.

Return Value: Returns an integer (int ≥ 0). If the element is not found, it returns 0.

Parameter Requirement: list.count() takes exactly one argument. Calling my_list.count() with zero arguments or multiple arguments raises a TypeError.

Basic Counting Examples 🔝

Here is a basic demonstration of counting strings and numbers in a list:

fruits = ["apple", "banana", "apple", "orange", "apple", "banana"]

apple_count = fruits.count("apple")
banana_count = fruits.count("banana")
orange_count = fruits.count("orange")

print("Apples: ", apple_count)
print("Bananas:", banana_count)
print("Oranges:", orange_count)
Expected Output
Apples:  3
Bananas: 2
Oranges: 1

Non-Existent Elements & Error Safety 🔝

Unlike list.index() or list.remove() which raise a ValueError when an item does not exist, list.count() returns 0 safely:

numbers = [10, 20, 30, 40]

print(numbers.count(99))  # Returns 0 without error
print(numbers.count("10")) # String '10' != integer 10 -> Returns 0

Because it returns 0, you can use list.count() in boolean checks (e.g. if my_list.count(x) > 0:), although the Pythonic membership test if x in my_list: is preferred because in stops as soon as the first match is found, while count() always scans the entire list.

The Equality Trap: Booleans, Floats & Integers 🔝

Because list.count() checks value equality (==) rather than object identity (is), subtle surprises can occur when lists contain mixed types:

1. Booleans and Integers

In Python, bool is a subclass of int, where True == 1 and False == 0:

mixed = [1, True, 0, False, "1"]

print("Count of 1:    ", mixed.count(1))     # Returns 2 (1 and True)
print("Count of True: ", mixed.count(True))  # Returns 2 (True and 1)
print("Count of 0:    ", mixed.count(0))     # Returns 2 (0 and False)
print("Count of '1':  ", mixed.count("1"))   # Returns 1 (Exact string only)

2. Floating-Point Numbers and Integers

Similarly, mathematical equality holds across numeric types:

numbers = [5, 5.0, 5.00]
print(numbers.count(5))  # Returns 3 because 5 == 5.0

Counting in Nested & 2D Lists 🔝

When working with 2D lists (matrices or tables), list.count() only counts exact matching sublists at the top level:

matrix = [[1, 2], [3, 4], [1, 2]]

# Counting sublists
print(matrix.count([1, 2]))  # Returns 2

# Attempting to count internal elements
print(matrix.count(1))        # Returns 0 (1 is inside sublists, not at root)

# To count occurrences across all nested sublists, sum individual row counts:
total_ones = sum(row.count(1) for row in matrix)
print("Total nested ones:", total_ones)  # Returns 2

Custom Classes & the __eq__() Method 🔝

When searching for instances of user-defined classes, list.count() delegates to your class's __eq__() method. By customizing __eq__(), you can count objects based on specific attributes (like an ID, SKU, or email):

class UserAccount:
    def __init__(self, user_id, username):
        self.user_id = user_id
        self.username = username

    def __eq__(self, other):
        if isinstance(other, UserAccount):
            return self.user_id == other.user_id
        return False

users = [
    UserAccount(101, "alice"),
    UserAccount(102, "bob"),
    UserAccount(101, "alice_backup")
]

target = UserAccount(101, "any_name")
print("Matches for user_id 101:", users.count(target))  # Returns 2

Time Complexity & the collections.Counter Alternative 🔝

Each call to list.count() performs a linear scan through the entire list, with a time complexity of Ο(n).

Performance Anti-Pattern: Calling count() inside a loop over the same list creates Ο(n2) quadratic performance!
# SLOW: O(n^2) time complexity!
frequencies = {item: my_list.count(item) for item in set(my_list)}

When you need to count frequencies for multiple or all items in a list, use Python's built-in collections.Counter. It scans the list once in Ο(n) time and provides instant Ο(1) lookups:

from collections import Counter

votes = ["Red", "Blue", "Red", "Green", "Blue", "Red"]

# Fast O(n) frequency table
vote_counts = Counter(votes)

print("Red votes:  ", vote_counts["Red"])
print("Blue votes: ", vote_counts["Blue"])
print("Top 2 Votes:", vote_counts.most_common(2))
Technique Time Complexity Space Complexity Best Used For
list.count(x) Ο(n) per call Ο(1) Checking the count of a single specific item once.
collections.Counter(lst) Ο(n) total Ο(k) unique items Counting all items, building frequency tables, finding top-k items.
x in list Ο(n) worst-case Ο(1) Checking existence (early exit on first match).

Hands-on Exercise: Shopping Cart Frequency with Assertions 🔝

Let's build a shopping cart quantity and discount checker using list.count(), verified with unit assertions:

Python Exercise: Cart Item Frequency & Bundle Discount Validator
def calculate_cart_summary(cart, promo_item, bundle_threshold=3):
    item_count = cart.count(promo_item)
    qualifies_discount = item_count >= bundle_threshold
    
    return {
        "item": promo_item,
        "quantity": item_count,
        "discount_applied": qualifies_discount
    }

test_cart = ["laptop", "mouse", "mouse", "keyboard", "mouse"]

mouse_summary = calculate_cart_summary(test_cart, "mouse", bundle_threshold=3)
laptop_summary = calculate_cart_summary(test_cart, "laptop", bundle_threshold=3)
headphone_summary = calculate_cart_summary(test_cart, "headphones", bundle_threshold=3)

# Unit Assertions
assert mouse_summary["quantity"] == 3
assert mouse_summary["discount_applied"] is True

assert laptop_summary["quantity"] == 1
assert laptop_summary["discount_applied"] is False

assert headphone_summary["quantity"] == 0
assert headphone_summary["discount_applied"] is False

print("Mouse Summary:     ", mouse_summary)
print("Headphone Summary: ", headphone_summary)
print("All shopping cart count assertions passed successfully!")



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-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer