Below are the three solutions:
Fastest is using a for loop and storing it in a Dict.
import time from collections import Counter def countElement(a): g = {} for i in a: if i in g: g[i] +=1 else: g[i] =1 return g z = [1,1,1,1,2,2,2,2,3,3,4,5,5,234,23,3,12,3,123,12,31,23,13,2,4,23,42,42,34,234,23,42,34,23,423,42,34,23,423,4,234,23,42,34,23,4,23,423,4,23,4] #Solution 1 - Faster st = time.monotonic() for i in range(1000000): b = countElement(z) et = time.monotonic() print(b) print('Simple for loop and storing it in dict - Duration: {}'.format(et - st)) #Solution 2 - Fast st = time.monotonic() for i in range(1000000): a = Counter(z) et = time.monotonic() print (a) print('Using collections.Counter - Duration: {}'.format(et - st)) #Solution 3 - Slow st = time.monotonic() for i in range(1000000): g = dict([(i, z.count(i)) for i in set(z)]) et = time.monotonic() print(g) print('Using list comprehension - Duration: {}'.format(et - st))Result
#Solution 1 - Faster{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 234: 3, 23: 10, 12: 2, 123: 1, 31: 1, 13: 1, 42: 5, 34: 4, 423: 3} Simple for loop and storing it in dict - Duration: 12.032000000000153
#Solution 2 - FastCounter({23: 10, 4: 6, 2: 5, 42: 5, 1: 4, 3: 4, 34: 4, 234: 3, 423: 3, 5: 2, 12: 2, 123: 1, 31: 1, 13: 1}) Using collections.Counter - Duration: 15.889999999999418
#Solution 3 - Slow{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 34: 4, 423: 3, 234: 3, 42: 5, 12: 2, 13: 1, 23: 10, 123: 1, 31: 1} Using list comprehension - Duration: 33.0
Python | Count occurrences of an element in a list
Given a list in Python and a number x, count number of occurrences of x in the given list.
Examples:
Method 1 (Simple approach)
We keep a counter that keeps on increasing if the required element is found in the list.
# Python code to count the number of occurrences
def countX(lst, x):
count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
# Driver Code
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x, countX(lst, x)))
|
Method 2 (Using count())
The idea is to use list method count() to count number of occurrences.
# Python code to count the number of occurrences
def countX(lst, x):
return lst.count(x)
# Driver Code
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x, countX(lst, x)))
|
Method 2 (Using Counter())
Counter method returns a dictionary with occurrences of all elements as a key-value pair, where key is the element and value is the number of times that element has occurred.
from collections import Counter
# declaring the list
l = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
# driver program
x = 3
d = Counter(l)
print('{} has occurred {} times'.format(x, d[x]))
|
Python List count()
In this tutorial, we will learn about the Python List count() method with the help of examples.
The count() method returns the number of times the specified element appears in the list.
Example
# create a list numbers = [2, 3, 5, 2, 11, 2, 7]How to count the number of occurrences of a list item in Python
Use .count() to Count Number of Occurrences in a Python List
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python .count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.
Let’s see how we can use the .count() method to count the number of occurrences in a Python list:
We can see here that when we apply the .count() method to a list and pass in the item that we want to count, that the number of occurrences are returned.
Let’s see what would happen if we pass in an item that does not exist in the list:
# Count the Number of Occurrences in a Python list using .count() items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b'] count_f = items.count('f') print(f'{count_f=}') # Returns: count_f=0When an item doesn’t exist in a list and the .count() method is applied, the value of 0 is returned.
This method is a very Pythonic way to get the number of occurrences in a Python list for a single item. However, if you wanted to count the number occurrences of more than one item in a list, it’d be much better to use a different method, such as the Counter library.
This is exactly what you’ll learn in the next section!
Need to automate renaming files? Check out this in-depth guide on using pathlib to rename files. More of a visual learner, the entire tutorial is also available as a video in the post!