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]]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Python | Split list of strings into sublists based on length
- Python | Sort all sublists in given list of strings
- Python | Count the sublists containing given element in a list
- Python | Remove repeated sublists from given list
- Python - Group Sublists by another List
- Print all sublists of a list in Python
- Python | Sort list of lists by the size of sublists
- Python | Count unique sublists within list
- Python | Pandas Split strings into two List/Columns using str.split()
- Python | Remove all sublists outside the given range
- Python | Swapping sublists over given range
- Python - Split a String by Custom Lengths
- Python | Merge elements of sublists
- Python | Print the common elements in all sublists
- Python | Merge corresponding sublists from two different lists
- Python | Adding value to sublists
- Python | Remove sublists that are present in another sublist
- Python | Add the occurrence of each number as sublists
- Python - Value list lengths
- Python - List lengths as record attribute
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.