Python | Split a list into sublists of given lengths
Last Updated :
20 Feb, 2023
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.
Python3
from itertools import islice
Input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
length_to_split = [ 2 , 1 , 3 , 1 ]
Inputt = iter ( Input )
Output = [ list (islice(Inputt, elem))
for elem in length_to_split]
print ( "Initial list is:" , Input )
print ( "Split length list: " , length_to_split)
print ( "List after splitting" , Output)
|
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]]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2: Using zip is another way to split a list into sublists of given length.
Python3
from itertools import accumulate
Input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
length_to_split = [ 2 , 2 , 3 , 3 ]
Output = [ Input [x - y: x] for x, y in zip (
accumulate(length_to_split), length_to_split)]
print ( "Initial list is:" , Input )
print ( "Split length list: " , length_to_split)
print ( "List after splitting" , Output)
|
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]]
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...