# Python – Extract elements from Ranges in List

PythonServer Side ProgrammingProgramming

When it is required to extract element from ranges in a list, a simple iteration and the ‘extend’ method is used.

## Example

Below is a demonstration of the same −

my_list = [14, 55, 41, 14, 17, 59, 22, 25, 14, 69, 42, 66, 99, 19]

print("The list is :")
print(my_list)

range_list = [(12, 14), (17, 18), (22, 28)]
print("The list is :")
print(range_list)

my_result = []
for element in range_list:

my_result.extend(my_list[element[0] : element[1] + 1])

print("The result is :")
print(my_result)

## Output

The list is :
[14, 55, 41, 14, 17, 59, 22, 25, 14, 69, 42, 66, 99, 19]
The list is :
[(12, 14), (17, 18), (22, 28)]
The result is :
[99, 19]

## Explanation

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

• Another list of tuple is defined and displayed on the console.

• An empty list is defined.

• The list is iterated over, and the zeroth element, and first element incremented 1 is added to the empty list.

• This is done using the ‘extend’ method.

• This is the output that is displayed on the console.

Published on 08-Sep-2021 08:25:53