Open In App

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

Last Updated : 18 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list of elements, a value k and a number n. The task is to check if the value k appears at least n times in the list. For example, if the input list is [1,2 3, 1, 1, 4], k = 1 and n = 3, the output should be True because 1 appears 3 times.

Using count()

We can use the count() method of lists to directly find how many times k occurs in the list. This method is efficient as it avoids manual iteration and gives the count in a single step.

Python
a = [1, 2, 3, 1, 1, 4]
b = 1
c = 3
print(a.count(b) >= c)

Output
True

Explanation:

  • The count method calculates how many times the value b occurs in the list a.
  • We compare this count with c to check if the condition is satisfied.
  • This is the simplest and most efficient way to solve the problem.

Let's explore some more methods and see how we can check if k occurs atleast n times in a list.

Using loop

We can manually iterate over the list and maintain a counter to check how many times k appears. This allows for early termination when the condition is satisfied.

Python
a = [1, 2, 3, 1, 1, 4]
b = 1
c = 3
d = 0
for x in a:
    if x == b:
        d += 1
    if d >= c:
        break
print(d >= c)

Output
True

Explanation:

  • A variable d is used to keep track of how many times b occurs in the list.
  • The for loop breaks as soon as d reaches or exceeds c, making this approach more efficient than counting all occurrences unnecessarily.
  • This method avoids unnecessary iterations and is easy to follow.

Using dictionary

We can use a dictionary to keep track of how many times each element occurs in the list. Then, we check the count for k.

Python
a = [1, 2, 3, 1, 1, 4]
b = 1
c = 3
d = {}
for x in a:
    d[x] = d.get(x, 0) + 1
print(d.get(b, 0) >= c)

Output
True

Explanation:

  • A dictionary d is used to store the count of each element in the list.
  • The get method retrieves the count of b, defaulting to 0 if b is not present in the dictionary.
  • This method is useful if we need to count multiple elements, but it is less direct for checking a single value.

Using list comprehension

We can use a list comprehension to create a list of elements equal to k and then check its length against n.

Python
a = [1, 2, 3, 1, 1, 4]
b = 1
c = 3
print(len([x for x in a if x == b]) >= c)

Output
True

Explanation:

  • list comprehension generates a new list containing all elements equal to b.
  • The length of this new list is compared with c to determine if the condition is satisfied.

Next Article

Similar Reads