![]() |
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 PythonBelow are some of the ways by which we can split a list into sub-lists based on index ranges in Python:
Split a List into Sub-Lists Using List ComprehensionIn this example, the below code generates the sub-lists by using list comprehension and slicing on the index ranges. Python3
Output
[[2, 3, 4, 5], [4, 5, 6, 7, 8]] Split a List into Sub-Lists Using append() Function and SlicingIn 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
Output
[[4, 15, 6], [6, 17, 8, 9]] Split a List into Sub-Lists Using itertools ModuleIn 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
Output
[[2, 13, 4, 15], [4, 15, 6, 7]] |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |