Write a Python Program to Remove Consecutive K element records


The program is a python script that removes sublists from a list of tuples based on a specific condition.

Here's what the program does in detail:

  • A list of tuples "val" is defined with 4 tuples each containing 4 elements.
  • The original list is printed using the "print()" function and the "str()" function to convert the list to a string.
  • The variable "K" is defined with a value 'C'.
  • 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 there are two consecutive elements in a tuple that are equal to the value of "K". This check is done using the "any()" function and a nested for loop that iterates over the elements in the range from 0 to len(i) - 2. If the condition is not met for a given tuple, it is added to the "res" list.
  • The final list "res" is printed after the removal of the tuples that contain two consecutive elements equal to "K".

Source Code

val = [('A', 'B', 'C', 'D'), ('B', 'C', 'C', 'I'), ('H', 'D', 'B', 'C'), ('C', 'C', 'G', 'F')]
print("Original List : " + str(val))
K = 'C'
res = [i for i in val if not any(i[j] == K and i[j + 1] == K for j in range(len(i) - 1))]
 
print("After Removal : " , res)

Output

Original List : [('A', 'B', 'C', 'D'), ('B', 'C', 'C', 'I'), ('H', 'D', 'B', 'C'), ('C', 'C', 'G', 'F')]
After Removal :  [('A', 'B', 'C', 'D'), ('H', 'D', 'B', 'C')]


Example Programs