Python program to check if given value occurs atleast k times

Given a list and some value (let’s say it N), write a Python program to check if the given value occurs atleast k-times in that list.

We can use list comprehension to deal with this problem. We can add each occurrence of given value and check if it is greater than or equal to k. If the value returned is True, then set the flag to 1, else 0.

Below is the Python implementation –

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to check if given
# value occurs atleast k times
  
test_list = [1, 3, 5, 5, 4, 5
    
# printing original list 
print ("The original list is : " + str(test_list)) 
    
# value to be checked  
val = 5
    
# initializing k 
k = 3
    
# using sum() + list comprehension 
# checking occurrences
res = 0
res = sum([1 for i in test_list if i == val]) >= k
   
if res == 1 : res = True
else :  res = False
        
# printing result  
print ("%d occur atleast %d times ? :" %(val, k) + str(res)) 

chevron_right


Output:

The original list is : [1, 3, 5, 5, 4, 5]
5 occur atleast 3 times ? :True


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.