Python list.count(): Expert Guide with Practical Examples
What is list.count()
Python’s built‑in list.count() method returns the number of times a specified element appears in a list. It also works on strings, making it a versatile tool for data analysis, text processing, and more.
How It Works
Syntax: list_obj.count(element)
Parameter: element – the value whose occurrences you want to count.
Return Value: An integer representing the count, or 0 if the element is absent.
Example 1: Counting Colors in a List
colors = ['red', 'green', 'blue', 'orange', 'green', 'gray', 'green']
green_count = colors.count('green')
print('The count of green:', green_count)
Output:
The count of green: 3
Example 2: Counting Duplicate Numbers
numbers = [2, 3, 4, 3, 10, 3, 5, 6, 3]
threes = numbers.count(3)
print('The count of 3:', threes)
Output:
The count of 3: 4
When to Use list.count()
- Quickly find the frequency of a specific value.
- Validate that a list contains expected duplicates.
- Integrate with data pipelines where element frequencies drive logic.
Performance Note
The method scans the entire list, so its time complexity is O(n). For large datasets, consider using collections.Counter for multi‑element counts.
Summary
- list.count() is a reliable, built‑in way to obtain element frequencies.
- It returns an integer and works on both lists and strings.
- Use it when you need a quick, single‑value count.
Python
- Python List Operations: Creation, Access, Modification, and Advanced Techniques
- Python Print() Function: A Practical Guide with Examples
- Master Python’s str.count(): How to Count Characters & Substrings with Examples
- Master Python `format()` Strings with Clear Examples
- Master Python's String.find() Method: Syntax, Examples & Alternatives
- Master Python Lambda Functions: Practical Examples & Best Practices
- Python round() Function Explained with Practical Examples
- Mastering Python's map() Function: Syntax, Examples, and Best Practices
- Python timeit() – Measuring Execution Time with Practical Examples
- Python Module Importing – A Practical Guide with Examples