Write a Python Program to Retain records with N occurrences of K


The program is a python script that filters a list of tuples based on the count of a specific element in each tuple.

Here's what the program does in detail:

  • A list of tuples "val" is defined with 4 tuples.
  • The original list "val" is printed using the "print()" function.
  • The variable "K" is defined with a value of 5 and the variable "N" is defined with a value of 2.
  • A list comprehension is used to create a new list "res" which contains only the tuples that meet a specific condition.
  • The condition used in the list comprehension checks if the count of the element "K" in a tuple is equal to the value of "N". This check is done using the "count()" method which returns the number of occurrences of a specified element in a tuple. If the count is equal to "N", the tuple is added to the "res" list.
  • The final list "res" is printed after the removal of the tuples that do not contain the specified count of the element "K".

Source Code

val = [(4, 5, 6, 5, 4), (4, 5, 3), (5, 5, 2), (3, 4, 9)]
print(val)
K = 5
N = 2
res = [e for e in val if e.count(K) == N]
 
print(res)

Output

[(4, 5, 6, 5, 4), (4, 5, 3), (5, 5, 2), (3, 4, 9)]
[(4, 5, 6, 5, 4), (5, 5, 2)]

Example Programs