Open In App

Python – Remove Consecutive K element records

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python records, we can have a problem in which we need to remove records on the basis of presence of consecutive K elements in tuple. This kind of problem is peculiar but can have applications in data domains. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [(4, 5), (5, 6), (1, 3), (0, 0)] K = 0 
Output : [(4, 5), (5, 6), (1, 3)] 

Input : test_list = [(4, 5), (5, 6), (1, 3), (5, 4)] K = 5 
Output : [(4, 5), (5, 6), (1, 3), (5, 4)]

Method #1 : Using zip() + list comprehension The combination of above functions can be used to solve this problem. In this, we need to combine two consecutive segments using zip() and perform the comparison in list comprehension. 

Python3




# Python3 code to demonstrate working of
# Remove Consecutive K element records
# Using zip() + list comprehension
 
# initializing list
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 6
 
# Remove Consecutive K element records
# Using zip() + list comprehension
res = [idx for idx in test_list if (K, K) not in zip(idx, idx[1:])]
 
# printing result
print("The records after removal : " + str(res))


Output : 

The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
The records after removal : [(4, 5, 6, 3), (1, 3, 5, 6)]

Time complexity: O(n*m), where n is the number of tuples in the list and m is the number of elements in each tuple.
Auxiliary space: O(n), where n is the number of tuples in the list. This is because the program creates a new list to store the filtered tuples.

Method #2 : Using any() + list comprehension The combination of above functions can be used to solve this problem. In this, we check for consecutive elements using any() and list comprehension is used to remake the list. 

Python3




# Python3 code to demonstrate working of
# Remove Consecutive K element records
# Using any() + list comprehension
 
# initializing list
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 6
 
# Remove Consecutive K element records
# Using any() + list comprehension
res = [idx for idx in test_list if not any(idx[j] == K and idx[j + 1] == K for j in range(len(idx) - 1))]
 
# printing result
print("The records after removal : " + str(res))


Output : 

The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
The records after removal : [(4, 5, 6, 3), (1, 3, 5, 6)]

The time complexity of the given code is O(nm), where n is the number of tuples in the list and m is the maximum length of a tuple. 

The auxiliary space used by the code is O(n), which is the space required to store the new list of tuples after the removal of consecutive K element records. 

Method #3: Using a for loop and a temporary list

This approach uses a nested for loop to iterate through each tuple in the list and each element within the tuple to check if there are any consecutive K elements. If there are, the tuple is skipped and not added to a temporary list. After iterating through all the tuples, the resulting temporary list is assigned to res.

Python3




test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
 
temp_list = []
for item in test_list:
    skip = False
    for i in range(len(item)-1):
        if item[i] == K and item[i+1] == K:
            skip = True
            break
    if not skip:
        temp_list.append(item)
res = temp_list
 
print("The records after removal : ", res)


Output

The records after removal :  [(4, 5, 6, 3), (1, 3, 5, 6)]

Time complexity: O(N*M), where N is the number of tuples in the list and M is the maximum length of a tuple..
Auxiliary space: O(N*M), where N is the number of tuples in the list and M is the maximum length of a tuple.

Method #4: Using filter() function 

In this method, we use the filter() function along with a lambda function. The lambda function checks if any consecutive elements in a tuple are equal to K using zip() and any() functions. If they are, then the filter() function removes that tuple from the list. The resulting list contains all tuples that do not have consecutive elements equal to K.

Python3




test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
 
res = list(filter(lambda x: not any(i == j == K for i, j in zip(x, x[1:])), test_list))
 
print("The records after removal : ", res)


Output

The records after removal :  [(4, 5, 6, 3), (1, 3, 5, 6)]

Time complexity: O(n*m), where n is the number of tuples in the list and m is the length of each tuple.
Auxiliary space: O(n), where n is the number of tuples in the list. 

Method 5: Using the itertools module

  • Import the itertools module.
  • Initialize an empty list called res.
  • Use the itertools.filterfalse() function to remove items that contain consecutive occurrences of K.
  • Convert the result to a list and assign it to res.
  • Return res.

Python3




import itertools
 
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
 
res = list(itertools.filterfalse(lambda item: any(item[i] == K and item[i+1] == K for i in range(len(item)-1)), test_list))
 
print("The records after removal : ", res)


Output

The records after removal :  [(4, 5, 6, 3), (1, 3, 5, 6)]

Time complexity: O(n^2), where n is the length of the longest item in test_list.
Auxiliary space: O(n), where n is the number of items in test_list.

Method 6: Using numpy:

Algorithm:

  1. Convert the list of tuples to a 2D NumPy array using np.array().
  2. Check if consecutive elements in each row are equal to K using the element-wise == operator and logical & operator to get a boolean array.
  3. Use np.any() with axis=1 to check if there is any True value in each row of the boolean array. This gives us a 1D boolean mask.
  4. Use np.logical_not() to negate the mask so that True values become False and vice versa.
  5. Filter the rows based on the mask using NumPy boolean indexing.
  6. Return the filtered rows as a NumPy array.

Python3




import numpy as np
 
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
K = 6
# printing original list
print("The original list is : " + str(test_list))
# Convert list of tuples to 2D NumPy array
arr = np.array(test_list)
 
# Check if consecutive elements in each row are equal to K
mask = np.logical_not(np.any((arr[:,:-1] == K) & (arr[:,1:] == K), axis=1))
 
# Filter the rows based on the mask
res = arr[mask]
 
print("The records after removal : ", res)
#This code is contributed by Vinay Pinjala


Output:
The original list is : [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
The records after removal :  [[4 5 6 3]
[1 3 5 6]]

Time complexity: O(nm), where n is the number of tuples and m is the number of elements in each tuple. Converting the list to a NumPy array takes O(nm) time. Checking for consecutive elements and applying the mask takes O(nm) time. Filtering the rows takes O(nm) time in the worst case if all rows pass the filter.

Space complexity: O(nm), where n is the number of tuples and m is the number of elements in each tuple. This is the space required to store the NumPy array.



Similar Reads

Python - Fill gaps in consecutive Records
Sometimes, while working with Python records, we can have a problem in which we have consecutive records, but a few missing and needs to be filled with any constant K. This kind of problem can have application in domains such as web development. Let's discuss certain ways in which we need to perform this task. Input : test_list = [(1, 4), (9, 11)]
3 min read
Python - Remove nested records from tuple
Sometimes, while working with records, we can have a problem in which an element of a record is another tuple records and we might have to remove the nested records. This is a problem which does not occur commonly, but having a solution to it is useful. Let’s discuss certain way in which this task can be performed. Method 1: Using loop + isinstance
5 min read
Python - Remove all duplicate occurring tuple records
Sometimes, while working with records, we can have a problem of removing those records which occur more than once. This kind of application can occur in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + set() + count() Initial approach that can be applied is that we can it
6 min read
Python - Remove None Nested Records
Sometimes, while working with Python Records, can have problem in which we need to perform the removal of data which have all key's values as None in nested records. This kind of problem can have application in data preprocessing. Lets discuss certain ways in which this task can be performed. Method #1 : Using all() + dictionary comprehension The c
4 min read
Python - Remove K from Records
Sometimes, while working with Python tuples, we can have a problem in which we need to remove all K from lists. This task can have application in many domains such as web development and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list = [(5, 6, 7), (2, 5, 7)] K = 7 Output : [(5, 6), (2, 5)] Inp
5 min read
Python - Remove records if Key not present
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the dictionaries in which a particular key is not present. This kind of problem can have applications in many domains such as day-day programming and data domain. Let's discuss certain ways in which this task can be performed. Input : test_list =
6 min read
Python - Rear element extraction from list of tuples records
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print specific information from the tuple like rear index. For instance, a piece of code would want just names to be printed on all the student data. Let's discuss certain ways in which one can achieve solutions to this problem. Method #1:
8 min read
Python - Summation in Dual element Records List
Sometimes, while working with Records list, we can have problem in which we perform the summation of dual tuple records and store it in list. This kind of application can occur over various domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension This is one of the way to solve this problem. In th
8 min read
Python groupby method to remove all consecutive duplicates
Given a string S, remove all the consecutive duplicates. Examples: Input : aaaaabbbbbb Output : ab Input : geeksforgeeks Output : geksforgeks Input : aabccba Output : abcba We have existing solution for this problem please refer Remove all consecutive duplicates from the string link. We can solve this problem in python quickly using itertools.group
2 min read
Python | Remove consecutive duplicates from list
In Python, we generally wish to remove the duplicate elements, but sometimes for several specific usecases, we require to have remove just the elements repeated in succession. This is a quite easy task and having a shorthand for it can be useful. Let's discuss certain ways in which this task can be performed. Method #1 : Using groupby() + list comp
4 min read
Practice Tags :