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

How to Split Lists in Python?

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 lists in Python.

Using List Slicing

The simplest way to split a list is by using slicing. This method allows you to divide a list into fixed-size chunks by specifying start and end indices. It is ideal when you know the desired size of each chunk.

Python
# Splitting a list into two parts li = [1, 2, 3, 4, 5, 6]  # Elements from index 0 to 2 a = li[:3]  # Elements from index 3 to end b = li[3:]    print(a, b) 

Output
[1, 2, 3] [4, 5, 6] 

Explanation: Slicing operator : is used to divide the list into two parts, with the first slice containing elements up to index 3 and the second slice starting from index 3.

Split list into chunks of equal size

For situations where you need to split a list into chunks of equal size, the list comprehension with slicing method can be used. This is particularly useful for large lists or when the exact size of chunks is known.

Python
# Splitting a list into equal-sized chunks li = [1, 2, 3, 4, 5, 6, 7, 8]  # Number of Chunks n = 3  # Splitting Chunks and Storing them in List a a = [li[i:i + n] for i in range(0, len(li), n)]  print(a) 

Output
[[1, 2, 3], [4, 5, 6], [7, 8]] 

Let's explore other methods of splitting lists in python:

Table of Content

  • Splitting Based on Conditions
  • Using itertools
  • Using numpy (For Advanced Operations)


Splitting Based on Conditions

For more control over splitting based on conditions, a loop can be used to separate elements based on custom logic.

Python
# Splitting a list based on a condition li = [1, 2, 3, 4, 5, 6, 7, 8] a = [] b = []  for i in li:   	     # Keeping the even numbers in list a after splitting     if i % 2 == 0:         a.append(i)              # Keeping the odd numbers in list b after splitting         else:         b.append(i)  print(a, b) 

Output
[2, 4, 6, 8] [1, 3, 5, 7] 

Explanation: This approach separates the list into two sublists based on whether the elements are even or odd.


Using itertools

We can use itertools.islice for split the list. This is efficient and you don't need to create intermediate copies of list, unlike slicing and list comprehension.

Python
from itertools import islice  a = [1, 2, 3, 4, 5, 6, 7, 8] n = 3  # Create an iterator it = iter(a)  # Use islice to generate chunks chunks = [] for _ in range(0, len(a), n):     chunks.append(list(islice(it, n)))  print(chunks)  # Output: [[1, 2, 3], [4, 5, 6], [7, 8]] 


Using numpy (For Advanced Operations)

We can also use the numpy library for advanced operations. The array_split method in numpy allows splitting a list into a specified number of sublists, distributing elements as evenly as possible.

Python
import numpy as np  # Splitting a list using numpy li = [1, 2, 3, 4, 5, 6, 7]  # Number of Chunks n = 3  # Keeping the chunks in list c after splitting c = np.array_split(li, n)  print([list(c) for i in c]) 

Output
[[array([1, 2, 3]), array([4, 5]), array([6, 7])], [array([1, 2, 3]), array([4, 5]), array([6, 7])], [array([1, 2, 3]), array([4, 5]), array([6, 7])]] 

Explanation: The numpy.array_split function divides the list into sublists, ensuring all elements are distributed.



Next Article
Python | Split list in uneven groups

A

anuragtriarna
Improve
Article Tags :
  • Python
  • Python Programs
  • python-list
  • Python list-programs
Practice Tags :
  • python
  • python-list

Similar Reads

  • How To Slice A List Of Tuples In Python?
    In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
    3 min read
  • Python | Split nested list into two lists
    Given a nested 2D list, the task is to split the nested list into two lists such that the first list contains the first elements of each sublist and the second list contains the second element of each sublist. In this article, we will see how to split nested lists into two lists in Python. Python Sp
    5 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 | 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
  • 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
  • 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 | Shift sublist in list
    Sometimes, while working with list, we can have a problem in which we need to shift some sublist to the desired index in the same sublist. This problem can occur in day-day programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using insert() + pop() + loop The comb
    5 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 - Split in Nested tuples
    Sometimes, while working with Python tuples, we can have a problem in which we need to perform split of elements in nested tuple, by a certain delimiter. This kind of problem can have application in different data domains. Let's discuss certain ways in which this task can be performed. Input : test_
    7 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