Sometimes, while working with Python list, we can have a problem in which we need to get the consecutive elements count remaining( including current ), to make certain decisions beforehand. This can be a potential subproblem of many competitive programming competitions. Let’s discuss a shorthand which can be applied to solve this problem.
Method : Using
range() + from_iterable() + groupby() + list comprehension
This task can be performed and solved using combination of above functions. In this, we first use groupby function to form groups and convert them into reverse ranges using
range(). This all is converted to generator to avoid creation of nested list and then final list is obtained using
The original list is : [4, 4, 5, 5, 5, 1, 1, 2, 4] Consecutive remaining elements list : [2, 1, 3, 2, 1, 2, 1, 1, 1]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Python - Retain first N Elements of a String and Replace the Remaining by K
- Python | Consecutive elements pairing in list
- Python | Group consecutive list elements with tolerance
- Python | Consecutive elements grouping in list
- Python | Consecutive duplicates all elements deletion in list
- Python | Concatenate N consecutive elements in String list
- Python - Multiply Consecutive elements in list
- Python - Consecutive K elements join in List
- Python - Extract range of Consecutive Similar elements ranges from string list
- Python program to check if the list contains three consecutive common numbers in Python
- Python | Remove consecutive duplicates from list
- Python | Average of each n-length consecutive segment in a list
- Python | Check if list contains consecutive numbers
- Python | Consecutive Maximum Occurrence in list
- Python | Identical Consecutive Grouping in list
- Python | Pair the consecutive character strings in a list
- Python - Ways to print longest consecutive list without considering duplicates element
- Python - Product of consecutive pairs in list
- Python - Maximum of Consecutive Pair in integer list
- Python - Consecutive Kth column Difference in Tuple List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.