Python | Split a list into sublists of given lengths
The problem of splitting a list into sublists is quite generic but to split in sublist of given length is not so common. Given a list of lists and list of length, the task is to split the list into sublists of given length.
Example:
Input : Input = [1, 2, 3, 4, 5, 6, 7]
length_to_split = [2, 1, 3, 1]
Output: [[1, 2], [3], [4, 5, 6], [7]]
Method #1: Using islice to split a list into sublists of given length, is the most elegant way.
# Python code to split a list # into sublists of given length. from itertools import islice # Input list initialization Input = [1, 2, 3, 4, 5, 6, 7] # list of length in which we have to split length_to_split = [2, 1, 3, 1] # Using islice Inputt = iter(Input) Output = [list(islice(Inputt, elem)) for elem in length_to_split] # Printing Output print("Initial list is:", Input) print("Split length list: ", length_to_split) print("List after splitting", Output) |
Initial list is: [1, 2, 3, 4, 5, 6, 7] Split length list: [2, 1, 3, 1] List after splitting [[1, 2], [3], [4, 5, 6], [7]]
Method #2: Using zip is another way to split a list into sublists of given length.
# Python code to split a list into # sublists of given length. from itertools import accumulate # Input list initialization Input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # list of length in which we have to split length_to_split = [2, 2, 3, 3] # Using islice Output = [Input[x - y: x] for x, y in zip( accumulate(length_to_split), length_to_split)] # Printing Output print("Initial list is:", Input) print("Split length list: ", length_to_split) print("List after splitting", Output) |
Initial list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Split length list: [2, 2, 3, 3] List after splitting [[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]]
Recommended Posts:
- Python | Split list of strings into sublists based on length
- Python | Print all sublists of a list
- Python | Remove repeated sublists from given list
- Python | Sort all sublists in given list of strings
- Python | Count unique sublists within list
- Python | Count the sublists containing given element in a list
- Python | Pandas Split strings into two List/Columns using str.split()
- Python | Sort list of lists by the size of sublists
- Python | Custom list split
- Python | Split list into lists by particular value
- Python | Split string into list of characters
- Python | Split nested list into two lists
- Python | Split a list having single integer
- Python | Split dictionary of lists to list of dictionaries
- Python | Split given list and insert in excel file
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



