Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Slice a 2D List in Python
Next article icon

Python - Cumulative List Split

Last Updated : 16 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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))  

Output
The 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))  

Output
The 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) 

Output
The 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. 

Output
The 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)) 

Output
The 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.


Next Article
Slice a 2D List in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences