- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Extract range of Consecutive similar elements ranges from string list
When it is required to extract range of consecutive similar elements ranges from list, a simple iteration and the ‘append’ method is used.
Below is a demonstration of the same −
my_list = [12, 23, 23, 23, 48, 48, 36, 17, 17] print("The list is : ") print(my_list) my_result =  index = 0 while index < (len(my_list)): start_position = index val = my_list[index] while (index < len(my_list) and my_list[index] == val): index += 1 end_position = index - 1 my_result.append((val, start_position, end_position)) print("The my_result is :") print(my_result)
The list is : [12, 23, 23, 23, 48, 48, 36, 17, 17] The my_result is : [(12, 0, 0), (23, 1, 3), (48, 4, 5), (36, 6, 6), (17, 7, 8)]
A list is defined and displayed on the console.
An empty list is created.
The value for index is defined as 0.
The list is iterated over, and a ‘while’ condition is placed.
This checks to see if the specific index is less than the length of the list and whether the specific value at the index is same as the previously defined values.
If yes, the index is incremented.
Otherwise, the index is decremented by 1 and assigned to another variable.
The integers are appended to the empty list.
This is the output that is displayed on the console.
- Python – Extract elements from Ranges in List
- Python program to extract characters in given range from a string list
- Python – Grouped Consecutive Range Indices of Elements
- Python - Consecutive Ranges of K greater than N
- Python – Extract String elements from Mixed Matrix
- Python – Extract tuples with elements in Range
- Consecutive elements pairing in list in Python
- Assign range of elements to List in Python
- Python – Extract elements in between multiple specific range of index
- Python Program to Extract Elements from a List in a Set
- Extract numbers from list of strings in Python
- Extract digits from Tuple list Python
- Python – Test if elements of list are in Min/Max range from other list
- Remove a range of elements from the List in C#
- Python – Extract Percentages from String