Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

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()

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

Python

  1. Python List Operations: Creation, Access, Modification, and Advanced Techniques
  2. Python Print() Function: A Practical Guide with Examples
  3. Master Python’s str.count(): How to Count Characters & Substrings with Examples
  4. Master Python `format()` Strings with Clear Examples
  5. Master Python's String.find() Method: Syntax, Examples & Alternatives
  6. Master Python Lambda Functions: Practical Examples & Best Practices
  7. Python round() Function Explained with Practical Examples
  8. Mastering Python's map() Function: Syntax, Examples, and Best Practices
  9. Python timeit() – Measuring Execution Time with Practical Examples
  10. Python Module Importing – A Practical Guide with Examples