Python – Extract elements from Ranges in List
Last Updated :
01 May, 2023
Given a list, and a list of tuples with ranges, extract all elements in those ranges from list.
Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 6, 10], range_list = [(2, 4), (7, 8)]
Output : [4, 6, 7, 5, 6]
Explanation : 4, 6, 7 are elements at idx 2, 3, 4 and 5, 6 at idx 7, 8.
Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 6, 10], range_list = [(2, 6)]
Output : [4, 6, 7, 5, 4]
Explanation : Elements from 2-6 index are extracted.
Method #1 : Using loop + list slicing
In this, we extract each range using list slicing and using loop iterate for each range and keep extending the extracting slices to extending list.
Python3
test_list = [ 4 , 5 , 4 , 6 , 7 , 5 , 4 , 5 , 4 , 6 , 4 , 6 , 9 , 8 ]
print ( "The original list is : " + str (test_list))
range_list = [( 2 , 4 ), ( 7 , 8 ), ( 10 , 12 )]
res = []
for ele in range_list:
res.extend(test_list[ele[ 0 ] : ele[ 1 ] + 1 ])
print ( "Ranges elements : " + str (res))
|
Output
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
Ranges elements : [4, 6, 7, 5, 4, 4, 6, 9]
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2: Using list comprehension
In this, we apply similar method as above function, difference being that list comprehension is used to solve this in compact form.
Python3
from itertools import chain
test_list = [ 4 , 5 , 4 , 6 , 7 , 5 , 4 , 5 , 4 , 6 , 4 , 6 , 9 , 8 ]
print ( "The original list is : " + str (test_list))
range_list = [( 2 , 4 ), ( 7 , 8 ), ( 10 , 12 )]
res = list (chain.from_iterable([test_list[ele[ 0 ] : ele[ 1 ] + 1 ] for ele in range_list]))
print ( "Ranges elements : " + str (res))
|
Output
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
Ranges elements : [4, 6, 7, 5, 4, 4, 6, 9]
Method 3 : Using map() and lambda function
Python3
test_list = [ 4 , 5 , 4 , 6 , 7 , 5 , 4 , 5 , 4 , 6 , 4 , 6 , 9 , 8 ]
range_list = [( 2 , 4 ), ( 7 , 8 ), ( 10 , 12 )]
res = list ( map ( lambda x: test_list[x[ 0 ]:x[ 1 ] + 1 ], range_list))
from itertools import chain
res = list (chain( * res))
print ( "Ranges elements : " + str (res))
|
Output
Ranges elements : [4, 6, 7, 5, 4, 4, 6, 9]
Time Complexity: O(n * m), where n is the length of the test_list and m is the number of ranges in range_list.
Auxiliary Space: O(k), where k is the total number of elements in the ranges in range_list.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...