Python – Extract elements in between multiple specific range of index

PythonServer Side ProgrammingProgramming

When it is required to extract elements that are in between multiple specific range of index, the ‘extend’ method, a simple iteration and indexing are used.

Example

Below is a demonstration of the same −

my_list = [13, 21, 81, 10, 13, 17, 22, 18, 11, 90, 0]

print("The list is : ")
print(my_list)
print("The list after sorting is : " )
my_list.sort()
print(my_list)

range_list = [(2, 4), (7, 8), (1, 2), (2,7)]

my_result = []
for element in range_list:
   my_result.extend(my_list[element[0] : element[1] + 1])

print("The resultant list is : ")
print(my_result)

print("The result after sorting is : " )
my_result.sort()
print(my_result)

Output

The list is :
[13, 21, 81, 10, 13, 17, 22, 18, 11, 90, 0]
The list after sorting is :
[0, 10, 11, 13, 13, 17, 18, 21, 22, 81, 90]
The resultant list is :
[11, 13, 13, 21, 22, 10, 11, 11, 13, 13, 17, 18, 21]
The result after sorting is :
[10, 11, 11, 11, 13, 13, 13, 13, 17, 18, 21, 21, 22]

Explanation

  • A list is defined and is displayed on the console.

  • It is sorted and displayed on the console.

  • Another list of tuples is defined. It indicates the ranges.

  • An empty list is defined.

  • The list is iterated over, and using list indexing the current and next element incremented by 1 are appended to the empty list.

  • This is displayed as output on the console.

  • It is sorted and displayed again on the console.

raja
Published on 13-Sep-2021 10:48:40
Advertisements