Python - Cumulative List Split
Last Updated : 16 May, 2023
Sometimes, while working with String lists, we can have a problem in which we need to perform the task of split and return all the split instances of list in cumulative way. This kind of problem can occur in many domains in which data is involved. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop
This is brute force way in which this task is performed. In this, we test for the list and append the list when ever we encounter the split character.
Python3 # Python3 code to demonstrate working of # Cumulative List Split # Using loop # initializing list test_list = ['gfg-is-all-best'] # printing original list print("The original list is : " + str(test_list)) # initializing Split char spl_char = "-" # Cumulative List Split # Using loop res = [] for sub in test_list: for idx in range(len(sub)): if sub[idx] == spl_char: res.append([ sub[:idx] ]) res.append([ sub ]) # printing result print("The Cumulative List Splits : " + str(res))
OutputThe original list is : ['gfg-is-all-best'] The Cumulative List Splits : [['gfg'], ['gfg-is'], ['gfg-is-all'], ['gfg-is-all-best']]
Time Complexity: O(n*n) where n is the total number of values in the list “test_list”.
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.
Method #2 : Using accumulate() + join()
This is one-liner approach to this problem. In this, we perform the task of cutting into cumulative using accumulate and join() is used to construct the resultant List of lists.
Python3 # Python3 code to demonstrate working of # Cumulative List Split # Using accumulate() + join() from itertools import accumulate # initializing list test_list = ['gfg-is-all-best'] # printing original list print("The original list is : " + str(test_list)) # initializing Split char spl_char = "-" # Cumulative List Split # Using accumulate() + join() temp = test_list[0].split(spl_char) res = list(accumulate(temp, lambda x, y: spl_char.join([x, y]))) # printing result print("The Cumulative List Splits : " + str(res))
OutputThe original list is : ['gfg-is-all-best'] The Cumulative List Splits : ['gfg', 'gfg-is', 'gfg-is-all', 'gfg-is-all-best']
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the accumulate() + join() which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #3: Using recursion
Python3 # Define a function to perform a cumulative list split def cumulative_list_split(lst, count): # Initialize an empty list to hold the result result = [] # Initialize an empty list to hold the current sublist sublist = [] # Iterate over the input list for i, item in enumerate(lst): # Add the current item to the sublist sublist.append(item) # If the length of the sublist is equal to the split count if (i + 1) % count == 0: # Join the sublist into a string and add it to the result list result.append(''.join(sublist)) # Reset the sublist to an empty list sublist = [] # If there are any remaining items in the sublist if sublist: # Join the remaining items into a string and add it to the result list result.append(''.join(sublist)) # Return the result list return result # Define a string to split my_string = 'gfg-is-all-best' # Convert the string to a list of characters my_list = list(my_string) # Perform a cumulative list split with a split count of 4 result_list = cumulative_list_split(my_list, 4) # Print the original string and the result list print("The original list is :", my_string) print("The Cumulative List Splits :", result_list)
OutputThe original list is : gfg-is-all-best The Cumulative List Splits : ['gfg-', 'is-a', 'll-b', 'est']
Time complexity: O(n)
Space complexity: O(n)
Method #4: Using reduce():
Step-by-step approach:
- Initialize the list test_list and print it.
- Initialize the splitter character spl_char and print it.
- Using reduce() and split(), iterate through each split and concatenate them with spl_char using lambda function.
- Append the split strings to a new list and store it in res variable.
- Print the result list.
Python3 from functools import reduce # initializing list test_list = ['gfg-is-all-best'] # printing original list print("The original list is : " + str(test_list)) # initializing Split char spl_char = "-" # Cumulative List Split # Using reduce() + split() + lambda res = reduce(lambda x, y: x + [spl_char.join(y)], [test_list[0].split(spl_char)[:i] for i in range(1, len(test_list[0].split(spl_char))+1)], []) # printing result print("The Cumulative List Splits : " + str(res)) #This code is contrinuted by Pushpa.
OutputThe original list is : ['gfg-is-all-best'] The Cumulative List Splits : ['gfg', 'gfg-is', 'gfg-is-all', 'gfg-is-all-best']
Time complexity: O(n^2), where n is the length of the input string, as we are using a nested for loop to generate all the possible substrings.
Auxiliary space: O(n^2), as we are storing all the possible substrings generated in a list. However, since the number of possible substrings is equal to the sum of the first n natural numbers, the worst-case space complexity can be approximated as O(n^2/2) = O(n^2).
Method #5: Using map() and list comprehension
In this method, we splits a string element in a list into its substrings using a specific character as a delimiter. The delimiter is stored in the variable spl_char. The list comprehension iterates over the string slices based on the split character using the join() method. The current slice is joined with the previous slices from 0 to i-1 (where i is the current iteration index), resulting in a cumulative split. All cumulative splits are stored in a list named res. Finally, the result is displayed using the print() function.
Python3 # initializing list test_list = ['gfg-is-all-best'] # printing original list print("The original list is : " + str(test_list)) # initializing Split char spl_char = "-" # Cumulative List Split # Using map() + join() + list comprehension res = [spl_char.join(test_list[0].split(spl_char)[:i]) for i in range(1, len(test_list[0].split(spl_char))+1)] # printing result print("The Cumulative List Splits : " + str(res))
OutputThe original list is : ['gfg-is-all-best'] The Cumulative List Splits : ['gfg', 'gfg-is', 'gfg-is-all', 'gfg-is-all-best']
Time complexity: O(n^2), where n is the length of the input string.
Auxiliary Space: O(n^2), as we are creating a list of length n(n+1)/2 to store all the possible substrings.
Similar Reads
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 flatten String List
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compr
7 min read
Python - Cumulative Records Product
Sometimes, while working with data in form of records, we can have a problem in which we need to find the product element of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method #1 :
5 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
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
Python program to find Cumulative sum of a list
Calculating the cumulative sum of a list means finding the running total of the elements as we move through the list. In this article, we will explore How to find the cumulative sum of a list. Using itertools.accumulate()This is the most efficient method for calculating cumulative sums. itertools mo
3 min read
Python - Cumulative Row Frequencies in List
Given Matrix, the task is to write a Python program to get total counts of occurrences from the row. Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]], ele_list = [1, 2, 7] Output : [2, 2, 2, 5] Explanation : 2 occurs 2 times in row 1 and so on. Input : test_list =
4 min read
Python | Custom List slicing Sum
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths and its summation according to the input given in other list. This problem has its potential application in web development. Letâs discuss certain ways in which this can be done. Me
7 min read
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 1: Us
6 min read
Python | Split given dictionary in half
While working with dictionaries, sometimes we might have a problem in which we need to reduce the space taken by single container and wish to divide the dictionary into 2 halves. Let's discuss certain ways in which this task can be performed. Method #1 : Using items() + len() + list slicing The comb
6 min read