Counting Occurrences of an Element in a List
In this section, we will learn how to count the number of times a specific element appears in a list.
Example
Input:
lst = [15, 6, 7, 10, 12, 20, 10, 28, 10] x = 10
Output:
3
Example 1: Using a Loop
def countX(lst, x): count = 0 for ele in lst: if ele == x: count += 1 return count lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print(countX(lst, x))
Output:
5
In this example, we manually iterate through the list and count the occurrences of the specified element using a loop.
Example 2: Using count()
Method
def countX(lst, x): return lst.count(x) lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print(countX(lst, x))
Output:
5
In this example, we use the built-in count()
method of the list to count the occurrences of the specified element.