Python | Split list in uneven groups
Last Updated :
09 May, 2023
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 1: 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
# 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))
Output : 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]]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using math
Take slice of original list from starting to ending and then append it to resultant split and then update
Step-by-Step algorithm
- we can start by computing the number of elements we want in each group.
- We can do this by dividing the total number of elements by the number of groups we want, and rounding up the result using the ceil function from the math module.
- This ensures that all groups except the last one have at least ceil(n/m) elements, where n is the total number of elements and m is the number of groups.
- We can then use a loop to iterate over the input list and split it into groups of the desired size.
- We can use the slice notation to extract a sublist of the input list starting at the current index and ending at the current index plus the desired group size. We can then append this sublist to the output list of groups, and increment the current index by the group size.
Python3
# Define the original list
original_list = [1, 4, 5, 7, 6, 5, 4, 2, 10]
# Define the split list with desired lengths
split_list = [3, 4, 2]
# Initialize an empty list to store the resultant split list
resultant_split_list = []
# Initialize a variable to keep track of the starting index of each slice in the original list
start_index = 0
# Iterate over the split list
for length in split_list:
# Take a slice of the original list starting from the start_index and ending at start_index + length
slice_list = original_list[start_index:start_index+length]
# Append the slice to the resultant split list
resultant_split_list.append(slice_list)
# Update the start_index to point to the start of the next slice
start_index += length
# Print the resultant split list
print(resultant_split_list)
Output[[1, 4, 5], [7, 6, 5, 4], [2, 10]]
Time complexity: O(n), where n is the length of the original list. This is because we are iterating over the original list once to create the slices, and the time taken to slice the list is proportional to its length.
Auxiliary Space: O(m), where m is the length of the split list. This is because we are creating a new list for each slice in the resultant split list, and the space taken by each slice is proportional to the length of the corresponding element in the split list.
Method #3: Using the Itertools Module:
Algorithm:
- Import the itertools module.
- Define the original list and split list.
- Use the accumulate function from itertools to calculate the cumulative sum of the split list.
- Use a list comprehension to iterate over the pairs of cumulative sums and calculate the slice of the original list using islice.
- Convert each slice to a list and append it to a new list to obtain the resultant split list.
- Print the resultant split list.
Python3
from itertools import accumulate, islice
original_list = [1, 4, 5, 7, 6, 5, 4, 2, 10]
# printing original list
print("The original list is : " + str(original_list))
split_list = [3, 4, 2]
# printing split list
print("The split list is : " + str(split_list))
res = [list(islice(original_list, start, end)) for start, end in zip([0]+list(accumulate(split_list)), accumulate(split_list))]
# printing result
print("The resultant split list is : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe 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]]
Time Complexity: O(n), where n is the total number of elements in the original list.
Auxiliary Space: O(m * k), where m is the length of the split list and k is the length of the longest slice.
Method #4: Use a while loop and slice
Python3
# Define the original list and split list with desired lengths
original_list = [1, 4, 5, 7, 6, 5, 4, 2, 10]
split_list = [3, 4, 2]
# Initialize an empty list to store the resultant split list
resultant_split_list = []
# Initialize a variable to keep track of the current position in the original list
pos = 0
# Iterate over the split list
for length in split_list:
# Use slicing to extract the current sublist from the original list
sublist = original_list[pos:pos+length]
# Append the sublist to the resultant split list
resultant_split_list.append(sublist)
# Update the current position in the original list
pos += length
# If there are any remaining elements in the original list, add them to the last sublist
if pos < len(original_list):
resultant_split_list[-1].extend(original_list[pos:])
# Print the resultant split list
print(resultant_split_list)
Output[[1, 4, 5], [7, 6, 5, 4], [2, 10]]
Time complexity of this approach is O(n^2) because the list comprehension inside the while loop iterates over all elements in the slice, which grows with each iteration.
The auxiliary space complexity is O(n), because we are creating a new slice list for each iteration.
Similar Reads
Python | Split tuple into groups of n
Given a tuple, the task is to divide it into smaller groups of n. Let's discuss a few methods to accomplish a given task.Method #1: Using enumerate and range function Python3 # Python code to demonstrate # how to split tuple # into the group of k-tuples # initialising tuple ini_tuple = (1, 2, 3, 4,
3 min read
How to Split Lists in Python?
Lists in Python are a powerful and versatile data structure. In many situations, we might need to split a list into smaller sublists for various operations such as processing data in chunks, grouping items or creating multiple lists from a single source. Let's explore different methods to split list
3 min read
Python - Vertical Grouping Value Lists
Sometimes, while working with Python dictionaries, we can have a problem in which we need to group all the list values vertically, i.e w.r.t similar index. This kind of problem can have applications in many domains such as web development. Let's discuss certain ways in which this problem can be solv
3 min read
Python | Custom list split
Development and sometimes machine learning applications require splitting lists into smaller list in a custom way, i.e on certain values on which split has to be performed. This is quite a useful utility to have knowledge about. Let's discuss certain ways in which this task can be performed. Method
8 min read
Python - Split heterogeneous type list
Sometimes, we might be working with many data types and in these instances, we can have a problem in which list that we receive might be having elements from different data types. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + isinstance() The
6 min read
Split list into lists by value - Python
The goal here is to split a list into sublists based on a specific value in Python. For example, given a list [1, 4, 5, 6, 4, 7, 4, 8] and a chosen value 4, we want to split the list into segments that do not contain the value 4, such as [[1], [5, 6], [7], [8]]. Letâs explore different approaches to
4 min read
Python | Group tuple into list based on value
Sometimes, while working with Python tuples, we can have a problem in which we need to group tuple elements to nested list on basis of values allotted to it. This can be useful in many grouping applications. Let's discuss certain ways in which this task can be performed. Method #1 : Using itemgetter
6 min read
Python | Grouping similar substrings in list
Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of grouping is useful in the cases of Machine Learning and Web Development. Let's discuss certain ways in which this can be done.
7 min read
Python - Convert Uneven Lists into Records
Sometimes, while working with Records, we can have a problem, that we have keys in one list and values in other. But sometimes, values can be multiple in order, like the scores or marks of particular subject. This type of problem can occur in school programming and development domains. Lets discuss
3 min read
Slice a 2D List in Python
Slicing a 2D list in Python is a common task when working with matrices, tables, or any other structured data. It allows you to extract specific portions of the list, making it easier to manipulate and analyze the data. In this article, we'll explore four simple and commonly used methods to slice a
4 min read