Python | Split list in uneven groups
Sometimes, while working with python, we can have a problem of splitting a list. This problem is quite common and has many variations. Having solutions to popular variations proves to be good in long run. Let’s discuss certain way to split list in uneven groups as defined by other list.
Method : Using itertools.islice() + list comprehension
The combination of above functionalities can be used to perform this task. In this, islice() is used to perform the core task of slicing the list and list comprehension is used to perform the task of binding together logic and iterations. The container is converted to iterator for faster iteration.
# Python3 code to demonstrate working of # Split list in uneven groups # using itertools.islice() + list comprehension from itertools import islice # initialize list test_list = [1, 4, 5, 7, 6, 5, 4, 2, 10] # initialize split list split_list = [3, 4, 2] # printing original list print("The original list is : " + str(test_list)) # printing split list print("The split list is : " + str(split_list)) # Split list in uneven groups # using itertools.islice() + list comprehension temp = iter(test_list) res = [list(islice(temp, 0, ele)) for ele in split_list] # printing result print("The resultant split list is : " + str(res)) |
The original list is : [1, 4, 5, 7, 6, 5, 4, 2, 10] The split list is : [3, 4, 2] The resultant split list is : [[1, 4, 5], [7, 6, 5, 4], [2, 10]]
Recommended Posts:
- Python | Split tuple into groups of n
- Python | Split string in groups of n consecutive characters
- Python | Pandas Split strings into two List/Columns using str.split()
- Python | Column summation in uneven sized lists
- Python | Find groups of strictly increasing numbers in a list
- Python | Custom list split
- Python | Split list into lists by particular value
- Python | Split a list having single integer
- Python | Split string into list of characters
- Python | Split a list into sublists of given lengths
- Python | Split nested list into two lists
- Python | Split given list and insert in excel file
- Python | Split strings in list with same prefix in all elements
- Python | Split and Pass list as separate parameter
- Python | Split dictionary of lists to list of dictionaries
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.



