Split a Python List into Sub-Lists Based on Index Ranges
Given a list of lists and a list of length, the task is to split the list into sublists based on the Index ranges. In this article, we will see how we can split list into sub-lists based on index ranges in Python.
Split a List into Sub-Lists Based on Index Ranges in Python
Below are some of the ways by which we can split a list into sub-lists based on index ranges in Python:
- Using list comprehension
- Using the append() function and slicing
- Using Itertools module
Split a List into Sub-Lists Using List Comprehension
In this example, the below code generates the sub-lists by using list comprehension and slicing on the index ranges.
Python3
Input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # The index ranges to split at indices = [( 1 , 4 ), ( 3 , 7 )] print ([ Input [a:b + 1 ] for (a, b) in indices]) |
[[2, 3, 4, 5], [4, 5, 6, 7, 8]]
Split a List into Sub-Lists Using append() Function and Slicing
In this example, below code generates the sub-lists based on Index ranges using for loop on the Index range list and appending each of the list generated by slicing through the input list to the final array.
Python3
Input = [ 3 , 4 , 15 , 6 , 17 , 8 , 9 ] # The index ranges to split at Index_list = [( 1 , 3 ), ( 3 , 6 )] result_list = [] for index_range in Index_list: result_list.append( Input [index_range[ 0 ]:index_range[ 1 ] + 1 ]) print (result_list) |
[[4, 15, 6], [6, 17, 8, 9]]
Split a List into Sub-Lists Using itertools Module
In this example, we have used the islice() function of the itertools module and list comprehension to split into sub-Lists. This islice() iterator selectively prints the values mentioned in its iterable container passed as an argument, iterate over the index range list and get each of the index range and pass the starting index and ending index to the islice() method as the parameters.
Python3
from itertools import islice # Input list initialization Input = [ 11 , 2 , 13 , 4 , 15 , 6 , 7 ] # list of length in which we have to split Index_range = [[ 1 , 4 ], [ 3 , 6 ]] # Using islice Output = [ list (islice( Input , elem[ 0 ], elem[ 1 ] + 1 )) for elem in Index_range] print (Output) |
[[2, 13, 4, 15], [4, 15, 6, 7]]