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 - Filter consecutive elements Tuples
Next article icon

Python – Squash consecutive values of K

Last Updated : 14 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python lists, we can have a problem in which we need to perform the removal of duplicate consecutive values of a particular element. This kind of problem can have applications in many domains such as competitive programming and web development. Let’s discuss certain ways in which this task can be performed.
 

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

Method #1 : Using zip() + yield 
The combination of the above functions provides one of the ways to solve this problem. In this, we perform the task of checking consecution duplications using zipping current and next element list, and yield is used to render the element basis of condition.
 

Python3




# Python3 code to demonstrate working of
# Squash consecutive values of K
# Using zip() + yield
 
# helper function
def hlper_fnc(test_list, K):
    for sub1, sub2 in zip(test_list, test_list[1:]):
        if sub1 == sub2 == K:
            continue
        else:
            yield sub1
    yield sub2      
 
# initializing list
test_list = [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 5
 
# Squash consecutive values of K
# Using zip() + yield
res = list(hlper_fnc(test_list, K))
 
# printing result
print("List after filtration : " + str(res))
 
 
Output : 
The original list is : [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5] List after filtration : [4, 5, 4, 3, 3, 5, 6, 5]

 

The time complexity of the program is O(n) because the helper function iterates through the input list once using the zip() function, which has a time complexity of O(n). Additionally, the yield statement in the helper function does not cause any extra iterations over the input list. The final list() function also has a time complexity of O(n) because it converts the generator object returned by the hlper_fnc() function into a list.

The auxiliary space complexity of the program is O(n) because the program creates a new list with filtered elements that can be as large as the original list. 

 
Method #2 : Using yield + groupby() 
The combination of the above functions can be used to solve this problem. In this, we perform the task of grouping using groupby(), for checking consecutions, and yield is used to return valid elements.
 

Python3




# Python3 code to demonstrate working of
# Squash consecutive values of K
# Using yield + groupby()
import itertools
 
# helper function
def hlper_fnc(test_list, K):
    for key, val in itertools.groupby(test_list):
        if key == K:
            yield key
        else:
            yield from val   
 
# initializing list
test_list = [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 5
 
# Squash consecutive values of K
# Using yield + groupby()
res = list(hlper_fnc(test_list, K))
 
# printing result
print("List after filtration : " + str(res))
 
 
Output : 
The original list is : [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5] List after filtration : [4, 5, 4, 3, 3, 5, 6, 5]

 

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.  yield + groupby() performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list



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

Similar Reads

  • Python - Extend consecutive tuples
    Given list of tuples, join consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Output : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2)] Explanation : Elements joined with their consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3)] Ou
    3 min read
  • Python | Consecutive Subsets Minimum
    Some of the classical problems in programming domain comes from different categories and one among them is finding the minimum of subsets. This particular problem is also common when we need to accumulate the minimum and store consecutive group minimum. Let’s try different approaches to this problem
    4 min read
  • Python - Consecutive Ranges of K greater than N
    Given a list of elements, the task is to write a Python program to get all ranges of K greater than N. Input : [2, 6, 6, 6, 6, 5, 4, 6, 6, 8, 4, 6, 6, 6, 2, 6], K = 6, N = 3 Output : [(1, 4), (11, 13)] Explanation : 6 is consecutive from index 1 to 4, hence 1-4 in result. 7-8 also has 6, but its les
    4 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 - Consecutive Tuple difference
    Given List of tuples, find index-wise absolute difference of consecutive tuples. Input : test_list = [(5, 3), (1, 4), (9, 5), (3, 5)] Output : [(4, 1), (7, 1), (6, 0)] Explanation : 5 - 1 = 4, 4 - 3 = 1. hence (4, 1) and so on. Input : test_list = [(9, 5), (3, 5)] Output : [(6, 0)] Explanation : 9 -
    4 min read
  • Python - K consecutive Maximum
    Given a List, find maximum of next K elements from each index. Input : test_list = [4, 3, 9, 2, 6, 12, 4, 3, 2, 4, 5], K = 4 Output : [9, 9, 9, 12, 12, 12, 4, 5] Explanation : Max of next 4 elements, (max(4, 3, 9, 2) = 9) Input : test_list = [4, 3, 9, 2, 6], K = 4 Output : [9, 9] Explanation : Max o
    4 min read
  • Python - Rearrange dictionary for consecutive value-keys
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to rearrange dictionary keys so as a value is followed by same key in dictionary. This problem can have application in competitive programming algorithms and Graph problems. Let's discuss certain ways in which
    4 min read
  • Python - Maximum element in consecutive subsets
    We are given a list of numbers and a fixed integer k. The task is to determine the maximum number in every consecutive block of k elements. For instance, consider the list [1,3,2,5,4,6,8,7] with k=3. This list can be divided into consecutive subsets: the first subset is [1,3,2], the next is [3,2,5]
    3 min read
  • Python | Chuncked summation every K value
    The prefix array is quite famous in the programming world. This article would discuss a variation of this scheme. To perform a chunked summation where the sum resets at every occurrence of the value K , we need to modify the summation logic. The idea is: Traverse the list.Keep adding to the cumulati
    3 min read
  • Creating Sets of Tuples in Python
    Tuples are an essential data structure in Python, providing a way to store ordered and immutable sequences of elements. When combined with sets, which are unordered collections of unique elements, you can create powerful and efficient data structures for various applications. In this article, we wil
    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