A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/break-list-chunks-size-n-python/ below:

Break a List into Chunks of Size N in Python

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:

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

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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4