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

When analyzing data in Python lists, you often need to check if a specific element appears at least N times. For example, determining if the number 5 appears at least 3 times in a list. This article demonstrates three efficient approaches to solve this problem.

Using Manual Counting

The most straightforward approach is to iterate through the list and count occurrences of the target element ?

data = [1, 3, 5, 5, 4, 5]
print("Given list:", data)

# Element to be checked
elem = 5
# Minimum required occurrences
n = 3

count = 0
for item in data:
    if item == elem:
        count += 1
        if count >= n:
            result = True
            break
else:
    result = False

print(f"Does {elem} occur at least {n} times? {result}")
Given list: [1, 3, 5, 5, 4, 5]
Does 5 occur at least 3 times? True

Using Built-in count() Method

Python's built-in count() method provides a cleaner solution ?

data = [2, 11, 9, 2, 4, 2]
print("Given list:", data)

# Element to be checked
elem = 2
# Minimum required occurrences
n = 3

result = data.count(elem) >= n
print(f"Does {elem} occur at least {n} times? {result}")
Given list: [2, 11, 9, 2, 4, 2]
Does 2 occur at least 3 times? True

Using itertools.islice for Early Termination

For large lists, you can use itertools.islice to stop counting once the threshold is reached ?

from itertools import islice

data = [7, 1, 7, 3, 7, 7, 5]
print("Given list:", data)

# Element to be checked
elem = 7
# Minimum required occurrences
n = 3

# Create generator for matching elements
matches = (True for item in data if item == elem)

# Check if we can find at least n matches
result = next(islice(matches, n-1, None), False)
print(f"Does {elem} occur at least {n} times? {result}")
Given list: [7, 1, 7, 3, 7, 7, 5]
Does 7 occur at least 3 times? True

Comparison

Method Time Complexity Best For
Manual counting O(n) - early termination Learning purposes
count() method O(n) - scans entire list Simple, readable code
islice approach O(n) - early termination Large lists, memory efficiency

Conclusion

Use the count() method for simple cases due to its readability. For large datasets where early termination matters, consider the manual counting or islice approach to improve performance.

---
Updated on: 2026-03-15T18:33:49+05:30

405 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements