
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Range of Consecutive Similar Elements from String List in Python
When it is required to extract range of consecutive similar elements ranges from list, a simple iteration and the ‘append’ method is used.
Example
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)
Output
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)]
Explanation
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.
Advertisements