Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Reorder for consecutive elements
Next article icon

Python – Remove Consecutive K element records

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.



Next Article
Python - Reorder for consecutive elements
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Reorder for consecutive elements
    Given a List perform reordering to get similar elements in consecution. Input : test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5] Output : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6] Explanation : All similar elements are assigned to be consecutive. Input : test_list = [4, 7, 5, 1, 4, 1, 6, 7, 5] Output : [4, 4, 7, 7,
    4 min read
  • Python | Retain K consecutive elements
    Sometimes while working with data, we can have a problem in which we need to select some of the elements that occur K times consecutively. This problem can occur in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using groupby() + list comprehension This tas
    8 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
    4 min read
  • Python - Test Consecutive Element Matrix
    Given a Matrix, test if it is made of consecutive elements. Input : test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]] Output : True Explanation : Elements in Matrix range from 4 to 12. Input : test_list = [[4, 5, 6], [7], [8, 18, 10], [11, 12]] Output : False Explanation : Elements not consecutive
    6 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,
    5 min read
  • 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
    3 min read
  • Python - Filter consecutive elements Tuples
    Given a Tuple list, filter tuples that are made from consecutive elements, i.e diff is 1. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 4), (6, 4, 6, 3)] Output : [(3, 4, 5, 6)] Explanation : Only 1 tuple adheres to condition. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6,
    5 min read
  • Python - Remove Columns of Duplicate Elements
    Given a Matrix, write a Python program to remove whole column if duplicate occurs in any row. Examples: Input : test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]] Output : [[4, 3, 5], [6, 4, 2], [4, 3, 9], [5, 4, 3]] Explanation : 1 has duplicate as next element hence 5
    3 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 whi
    6 min read
  • Python - Group Consecutive elements by Sign
    Given a list group of consecutive elements on the basis of signs. Input : test_list = [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3] Output : [[5], [-3], [2, 4, 6], [-2, -1, -7, -9], [2, 3]] Explanation : Elements inserted into new list on sign change.Input : test_list = [-2,3,4,5,6,-3] Output : [[-2], [3,
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences