0
0
PythonHow-ToBeginner · 3 min read

How to Count Occurrences of Element in List in Python

To count how many times an element appears in a list in Python, use the list.count(element) method. It returns the number of times the specified element occurs in the list.
📐

Syntax

The syntax to count occurrences of an element in a list is:

  • list.count(element): Calls the count method on the list.
  • element: The item you want to count in the list.
  • The method returns an integer representing how many times element appears.
python
count = my_list.count(element)
💻

Example

This example shows how to count the number of times the number 3 appears in a list.

python
my_list = [1, 3, 5, 3, 7, 3, 9]
count_3 = my_list.count(3)
print(f"Number 3 appears {count_3} times in the list.")
Output
Number 3 appears 3 times in the list.
⚠️

Common Pitfalls

Some common mistakes when counting elements in a list include:

  • Using count on a variable that is not a list, which causes an error.
  • Confusing the element type; for example, counting the integer 3 when the list contains strings like '3'.
  • Trying to count multiple elements at once, which count does not support.
python
my_list = [1, '3', 3, 3]

# Wrong: counting string '3' when you want integer 3
count_wrong = my_list.count('3')
print(f"Count of string '3': {count_wrong}")

# Right: counting integer 3
count_right = my_list.count(3)
print(f"Count of integer 3: {count_right}")
Output
Count of string '3': 1 Count of integer 3: 2
📊

Quick Reference

Remember these tips when counting elements in a list:

  • Use list.count(element) to get the count.
  • The method returns 0 if the element is not found.
  • It works only for one element at a time.
  • Make sure the element type matches exactly what is in the list.

Key Takeaways

Use list.count(element) to count how many times an element appears in a list.
The method returns 0 if the element is not present in the list.
Ensure the element type matches exactly to get correct counts.
You can only count one element at a time with count.
Calling count on non-list objects will cause errors.