Break a List into Chunks of Size N in Python
Last Updated :
20 Apr, 2025
The goal here is to break a list into chunks of a specific size, such as splitting a list into sublists where each sublist contains n elements. For example, given a list [1, 2, 3, 4, 5, 6, 7, 8] and a chunk size of 3, we want to break it into the sublists [[1, 2, 3], [4, 5, 6], [7, 8]]. Let’s explore different approaches to accomplish this.
Using List Comprehension
List comprehension is an efficient method for chunking a list into smaller sublists. This method creates a list of lists, where each inner list represents a chunk of the original list of a given size.
Python
a = [1, 2, 3, 4, 5, 6, 7, 8]
n = 3
res = [a[i:i + n] for i in range(0, len(a), n)]
print(res)
Output[[1, 2, 3], [4, 5, 6], [7, 8]]
Explanation:
- range(0, len(a), n) generates starting indices for each chunk, i.e., 0, 3, 6, etc.
- a[i:i + n] slices the list a starting at index i and ending at i + n (the chunk size).
- For each index in the range, the list is sliced into chunks of size n.
Using Slicing
This is a straightforward approach using a for loop to iterate over the list and slice it manually into chunks of size n. It’s simple to understand and works well for smaller datasets.
Python
a = [1, 2, 3, 4, 5, 6, 7, 8]
n = 3
res = []
for i in range(0, len(a), n): # Slice list in steps of n
res.append(a[i:i + n])
print(res)
Output[[1, 2, 3], [4, 5, 6], [7, 8]]
Explanation:
- For loop increments by n, ensuring each slice covers a chunk of size n.
- Each sliced chunk is appended to the chunks list.
For very large lists, itertools.islice can be a memory-efficient way to create chunks without loading the entire list into memory. It allows you to process the list incrementally.
Python
from itertools import islice
a = [1, 2, 3, 4, 5, 6, 7, 8]
n = 3
it = iter(a)
res = [list(islice(it, n)) for _ in range((len(a) + n - 1) // n)]
print(res)
Output[[1, 2, 3], [4, 5, 6], [7, 8]]
Explanation:
- iter(a) converts list a into an iterator it for sequential access to elements.
- islice(it, n) fetches n elements at a time from the iterator it using islice.
- for _ in range((len(a) + n - 1) // n) iterates the required number of times to generate chunks, ensuring even an incomplete final chunk is included.
Using numpy.array_split
For handling larger or more complex datasets, numpy offers the array_split() function. It automatically handles unequal chunk sizes, making it particularly useful when the list size is not perfectly divisible by n.
Python
import numpy as np
a = [1, 2, 3, 4, 5, 6, 7, 8]
n = 3
res = np.array_split(a, len(a) // n + (len(a) % n != 0))
res = [list(i) for i in res]
print(res)
Output[[np.int64(1), np.int64(2), np.int64(3)], [np.int64(4), np.int64(5), np.int64(6)], [np.int64(7), np.int64(8)]]
Explanation:
- array_split splits the list into chunks, automatically handling unequal chunk sizes.
- Each resulting numpy array is converted back into a Python list.
Similar Reads
How to Create a List of N-Lists in Python In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
3 min read
Break a list comprehension Python Python's list comprehensions offer a concise and readable way to create lists. While list comprehensions are powerful and expressive, there might be scenarios where you want to include a break statement, similar to how it's used in loops. In this article, we will explore five different methods to in
2 min read
How to split a Python list into evenly sized chunks Iteration in Python is repeating a set of statements until a certain condition is met. This is usually done using a for loop or a while loop. There are several ways to split a Python list into evenly sized-chunks. Here are the 5 main methods: Method 1: Using a Loop with List SlicingUse for loop alon
3 min read
How to Split a File into a List in Python In this article, we are going to see how to Split a File into a List in Python. When we want each line of the file to be listed at consecutive positions where each line becomes an element in the file, the splitlines() or rstrip() method is used to split a file into a list. Let's see a few examples
5 min read
Average of Each N-length Consecutive Segment in a List - Python The task is to compute the average of each n-length consecutive segment from a given list. For example, if the input list is [1, 2, 3, 4, 5, 6] and n = 2, the output should be [1.5, 2.5, 3.5, 4.5, 5.5]. Let's discuss various ways in this can be achieved.Using List ComprehensionThis method uses list
3 min read
Python | Group elements on break positions in list Many times we have problems involving and revolving around Python grouping. Sometimes, we might have a specific problem in which we require to split and group N element list on missing elements. Let's discuss a way in which this task can be performed. Method : Using itemgetter() + map() + lambda() +
2 min read
How to Get First N Items from a List in Python Accessing elements in a list has many types and variations. This article discusses ways to fetch the first N elements of the list.Using List Slicing to Get First N Items from a Python ListThis problem can be performed in 1 line rather than using a loop using the list-slicing functionality provided b
4 min read
Access List Items in Python Accessing elements of a list is a common operation and can be done using different techniques. Below, we explore these methods in order of efficiency and their use cases. Indexing is the simplest and most direct way to access specific items in a list. Every item in a list has an index starting from
2 min read
Python | Custom slicing in List Sometimes, while working with Python, we can come to a problem in which we need to perform the list slicing. There can be many variants of list slicing. One can have custom slice interval and slicing elements. Let's discuss problem to such problem. Method : Using compress() + cycle() The combination
2 min read