Python - Check if k occurs atleast n times in a list


Many times during data analysis using lists we come across a situation where we need to find out if a given element is present at least N Times in the given list. For example if 5 is present at least three times in the list or not. In this article we will see 2 approaches on how to achieve this.

Counting Occurrences

In the below approach we take the number and it's occurrences as an input. Then we e designer follow to keep the count of the occurrences. If the count value is greater than or equal to the required value then we print the result as true else false.

Example

listA = [1, 3, 5, 5, 4, 5]
# Given list
print("Given list: ",listA)
# element ot be checked
elem = 5
# Number of occurences
N = 3
res = 0
for e in listA:
   if e == elem:
      res = res + 1
      if res >= N:
         res = True
   else:
         res = False
# printing result
print("Does %d occur atleast %d times ? :" % (elem, N),res)

Running the above code gives us the following result −

Output

Given list: [1, 3, 5, 5, 4, 5]
Does 5 occur atleast 3 times ? : True

Using Islice and next

In this approach we create a new list containing the given number from the original list. This new list has all the occurrences of the given number marked as true. Then we design a islice method that will calculate if the required number of True values are present in the new list. Accordingly the number of required values is Mark does true or false.

Example

from itertools import islice
listA = [2, 11, 9,2, 4, 2]
# Given list
print("Given list: ",listA)
# element to be checked
elem = 2
# Number of occurrences
N = 3
elem_list = []
# Create
for i in listA:
   if i == elem:
      elem_list.append(True)
res = next(islice(elem_list, N-1, None), False)
# printing result
print("Does %d occur atleast %d times ? :" % (elem, N),res)

Running the above code gives us the following result −

Output

Given list: [2, 11, 9, 2, 4, 2]
Does 2 occur atleast 3 times ? : True

Updated on: 28-Dec-2020

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements