Skip to main content

How to count the occurrences of an element in a list in Python

How to count the occurrences of an element in a list in Python.

Here's a step-by-step tutorial on how to count the occurrences of an element in a list in Python.

1: Create a list

First, you need to create a list in Python. A list is a collection of elements enclosed in square brackets ([]). For example, let's create a list of numbers:

numbers = [1, 2, 3, 4, 2, 3, 2, 1, 5]

2: Use the count() method

Python provides a built-in count() method that allows you to count the occurrences of an element in a list. You can use this method to count how many times an element appears in the list.

count = numbers.count(2)
print(count)

In this example, we're using the count() method on the 'numbers' list to count the occurrences of the number 2. The count variable will store the result, and then we print it.

Output:

3

The output shows that the number 2 appears 3 times in the list.

3: Create a function to count occurrences

If you need to count the occurrences of an element in a list multiple times, it's better to create a function. Here's an example of how you can create a function to count occurrences:

def count_occurrences(lst, element):
count = lst.count(element)
return count

numbers = [1, 2, 3, 4, 2, 3, 2, 1, 5]
result = count_occurrences(numbers, 2)
print(result)

In this example, we define a function called count_occurrences that takes two parameters: lst (the list) and element (the element to count occurrences of). Inside the function, we use the count() method to count the occurrences of the element in the list, and then return the count.

Output:

3

The output is the same as before since we are counting the occurrences of the number 2 in the 'numbers' list.

4: Use a loop to count occurrences

If you don't want to use the count() method, you can also use a loop to iterate over the list and count the occurrences manually. Here's an example:

def count_occurrences(lst, element):
count = 0
for item in lst:
if item == element:
count += 1
return count

numbers = [1, 2, 3, 4, 2, 3, 2, 1, 5]
result = count_occurrences(numbers, 2)
print(result)

In this example, we define the count_occurrences function, which initializes the count variable to 0. We then iterate over each item in the list using a for loop. If the item is equal to the element we're counting, we increment the count by 1. Finally, we return the count.

Output:

3

Again, the output is the same as before since we are counting the occurrences of the number 2 in the 'numbers' list.

That's it! You now know how to count the occurrences of an element in a list in Python using different methods.