Horje
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:

  1. Using list comprehension
  2. Using the append() function and slicing
  3. 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])

Output

[[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)

Output

[[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)

Output

[[2, 13, 4, 15], [4, 15, 6, 7]]






Reffered: https://www.geeksforgeeks.org


Python

Related
Python Program to Convert Temperatures using Classes Python Program to Convert Temperatures using Classes
Sum Integers Stored in JSON using Python Sum Integers Stored in JSON using Python
Install Specific Version of Spacy using Python PIP Install Specific Version of Spacy using Python PIP
Sort a List of Python Dictionaries by a Value Sort a List of Python Dictionaries by a Value
How To Reverse A List In Python Using Slicing How To Reverse A List In Python Using Slicing

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12