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.
Input : Input = [1, 2, 3, 4, 5, 6, 7] length_to_split = [2, 1, 3, 1] Output: [[1, 2], , [4, 5, 6], ]
Method #1: Using
islice to split a list into sublists of given length, is the most elegant way.
Initial list is: [1, 2, 3, 4, 5, 6, 7] Split length list: [2, 1, 3, 1] List after splitting [[1, 2], , [4, 5, 6], ]
Method #2: Using
zip is another way to split a list into sublists of given length.
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]]
- 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 email@example.com. 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.