How to Split Lists in Python?
Last Updated :
26 Nov, 2024
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:
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.
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.
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