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:
Python | Split list in uneven groups
Next article icon

Python | Custom list split

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 #1 : Using list comprehension + zip() By coupling the power of list comprehension and zip(), this task can be achieved. In this, we zip beginning and end of list and then keep slicing the list as they arrive and cutting off new lists from them. 

Python3




# Python3 code to demonstrate
# to perform custom list split
# using list comprehension + zip()
 
# initializing string 
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
 
# initializing split index list
split_list = [2, 5, 7]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing original split index list
print ("The original split index list : " + str(split_list))
 
# using list comprehension + zip()
# to perform custom list split
res = [test_list[i : j] for i, j in zip([0] +
          split_list, split_list + [None])]
 
# printing result
print ("The splitted lists are : " +  str(res))
 
 
Output:
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4] The original split index list : [2, 5, 7] The splitted lists are : [[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(m), where m is the length of the split index list. 

Method #2 : Using itertools.chain() + zip() The task performed by the list comprehension function of getting the split chunks can also be done using chain function. This is more useful when we wish to handle larger lists as this method is more efficient. 

Python3




# Python3 code to demonstrate
# to perform custom list split
# using itertools.chain() + zip()
from itertools import chain
 
# initializing string 
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
 
# initializing split index list
split_list = [2, 5, 7]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing original split index list
print ("The original split index list : " + str(split_list))
 
# using itertools.chain() + zip()
# to perform custom list split
temp = zip(chain([0], split_list), chain(split_list, [None]))
res = list(test_list[i : j] for i, j in temp)
 
# printing result
print ("The splitted lists are : " +  str(res))
 
 
Output:
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4] The original split index list : [2, 5, 7] The splitted lists are : [[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]

Time complexity: O(n), where n is the length of the test_list, because we need to iterate over the entire list once.
Auxiliary space: O(k), where k is the number of split indices in the split_list, because we need to create a new list of length k+1 to store the split indices. 

Method #3 : Using slice() + iteration

Using the slice function to split the list into smaller lists. The slice function can be used to create a slice object representing a range of indices, which can then be passed as an argument to the list function to create a new list from the original list.

Python3




# initializing list
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
 
# initializing split index list
split_list = [2, 5, 7]
 
# printing original list
print("The original list is:", test_list)
 
# printing original split index list
print("The original split index list:", split_list)
 
# using the slice function to split the list
res = []
start = 0
for end in split_list:
    res.append(test_list[slice(start, end)])
    start = end
res.append(test_list[slice(start, len(test_list))])
 
# printing result
print("The splitted lists are:", res)
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
The original list is: [1, 4, 5, 6, 7, 3, 5, 9, 2, 4] The original split index list: [2, 5, 7] The splitted lists are: [[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]

Time complexity: O(n), where n is the length of the list. This is because the slice function has a time complexity of O(1) and the loop iterates over all elements in the list, resulting in a total time complexity of O(n).
Auxiliary space: O(n), since a new list is created for each split and the length of the new list is equal to the number of elements in the original list. This results in a total space complexity of O(n).

Method #4: Using a loop with range() and append()

Loop is used to iterate over the elements between each pair of split indices and append them to a temporary list. This temporary list is then added to the final result list.

Python3




# initializing list
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
 
# initializing split index list
split_list = [2, 5, 7]
 
# printing original list
print("The original list is:", test_list)
 
# printing original split index list
print("The original split index list:", split_list)
 
# using a loop to split the list
res = []
start = 0
for end in split_list:
    temp = []
    for i in range(start, end):
        temp.append(test_list[i])
    res.append(temp)
    start = end
temp = []
for i in range(start, len(test_list)):
    temp.append(test_list[i])
res.append(temp)
 
# printing result
print("The splitted lists are:", res)
 
 
Output
The original list is: [1, 4, 5, 6, 7, 3, 5, 9, 2, 4] The original split index list: [2, 5, 7] The splitted lists are: [[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]

Time complexity: O(n), where n is the length of the input list test_list. 
Auxiliary space: O(n), where n is the length of the input list test_list.

Method #5: Using the built-in function itertools.islice()

The itertools.islice() function returns an iterator that slices elements from a given iterable (in this case, the test_list) between a start and end index. We can use this function to split the list based on the values in the split_list.

Step-by-step approach:

  • Import the itertools module.
  • Initialize an empty list to hold the split lists.
  • Initialize a start index variable to 0.
  • Use the zip() function to iterate over pairs of consecutive values in the split_list.
  • For each pair of values (start, end) in the split_list, use itertools.islice() to slice the test_list between the start and end indices and append the result to the split list.
  • If there are any remaining elements in the test_list after the last split index, use itertools.islice() to slice those elements and append the result to the split list.
  • Return the split list.

Below is the implementation of the above approach:

Python3




import itertools
 
def split_list(test_list, split_points):
    splits = []
    start = 0
    for end in itertools.chain(split_points, [None]):
        split = list(itertools.islice(test_list, start, end))
        splits.append(split)
        start = end
    return splits
 
# Example usage:
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
split_points = [2, 5, 7]
result = split_list(test_list, split_points)
print(result)
 
 
Output
[[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]

Time complexity: O(n), where n is the length of the test_list.
Auxiliary space: O(m), where m is the number of splits (i.e. the length of the split_list plus 1.

Method #6: Using numpy:

Algorithm:

  1. Initialize the list test_list and the split index list split_list.
  2. Print the original list and the original split index list.
  3. Split the list using the slice function and append the resulting sublists to a new list res.
  4. Print the resulting sublists res.

Python3




import numpy as np
 
# initializing list
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
 
# initializing split index list
split_list = [2, 5, 7]
 
# printing original list
print("The original list is:", test_list)
 
# printing original split index list
print("The original split index list:", split_list)
 
# using NumPy to split the list
res = np.split(test_list, split_list)
res = [sublist.tolist() for sublist in res]
 
# printing result
print("The splitted lists are:", res)
#This code is contributed by Jyothi pinjala.
 
 
Output: The original list is: [1, 4, 5, 6, 7, 3, 5, 9, 2, 4] The original split index list: [2, 5, 7] The splitted lists are: [[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]

Time Complexity:
The time complexity of initializing the two lists is O(n), where n is the length of the test_list.
The time complexity of printing the two lists is also O(n).
The time complexity of the for loop that splits the list is O(k), where k is the length of the split_list.
The time complexity of the slice function is O(1) since it is a constant time operation.
Therefore, the total time complexity of the code is O(n+k).

Auxiliary Space:
The space complexity of the code is O(n) because we are creating a new list res to store the resulting sublists, and this list can have up to n elements (if split_list is empty).
Note that the space complexity of the original list and the split index list is not counted because they are part of the input.



Next Article
Python | Split list in uneven groups
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Cumulative List Split
    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
    6 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
  • 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 - Split a String by Custom Lengths
    Given a String, perform split of strings on the basis of custom lengths. Input : test_str = 'geeksforgeeks', cus_lens = [4, 3, 2, 3, 1] Output : ['geek', 'sfo', 'rg', 'eek', 's'] Explanation : Strings separated by custom lengths.Input : test_str = 'geeksforgeeks', cus_lens = [10, 3] Output : ['geeks
    2 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 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 - Access List Item
    Whether we are working with numbers, strings or other data types, lists provide a versatile way to organize and manipulate data. But how to access specific items in a list? This article will guide you through various methods of accessing list items in Python. Accessing List Items by IndexIn Python,
    3 min read
  • Python - Sublist Maximum in custom sliced List
    Sometimes, while working with data, we can have a problem in which we need to extract maximum not of whole list but of certain customly broken sublists. This kind of problem is peculiar and occurs in many domains. Let's discuss certain ways in which in which this task can be performed. Method #1 : U
    5 min read
  • re.split() in Python
    The re.split() method in Python is used to split a string by a pattern (using regular expressions). It is part of the re-module, which provides support for working with regular expressions. This method is helpful when we need to split a string into multiple parts based on complex patterns rather tha
    3 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
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