Python – Extract range of Consecutive similar elements ranges from string list

PythonServer Side ProgrammingProgramming

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.

raja
Published on 08-Sep-2021 10:43:28
Advertisements