Sometimes while working with data, we can have a problem in which we need to select some of the elements that occur range 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 task can be performed using above functionalities. In this, we group all the numbers that are occurring range consecutively. We iterate the list using list comprehension.
The original list : [1, 1, 4, 5, 5, 6, 7, 7, 7, 8, 8, 8, 8] The range consecutive elements are : [1, 5, 7]
Method #2 : Using list comprehension +
slice() + groupby()
This task can also be performed using above functions. In this, we just perform grouping in similar way as above but the way we extract consecutive elements is by
The original list : [1, 1, 4, 5, 5, 6, 7, 7, 7, 8, 8, 8] The range consecutive elements are : [1, 5, 7, 8]
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 - Extract range of Consecutive Similar elements ranges from string list
- Python - Extract tuples with elements in Range
- Python - Extract range sized strings
- Python - Extract range characters from String
- Python program to extract characters in given range from a string list
- Python - Grouped Consecutive Range Indices of Elements
- Python | Extract similar index elements
- Python - Extract dictionary items with List elements
- Python - Extract Even elements in Nested Mixed Tuple
- Python - Extract Kth index elements from Dictionary Value list
- Python - Extract records if Kth elements not in List
- Python - Extract elements with Frequency greater than K
- Python - Extract elements from Ranges in List
- Python - Extract String elements from Mixed Matrix
- Python - Extract Monodigit elements
- Python program to extract the Unique Dictionary Value List elements
- Python - Extract tuples having K digit elements
- Python - Extract elements with equal frequency as value
- Python | Extract key-value of dictionary in variables
- Python Regex to extract maximum numeric value from a string
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.