Home >Backend Development >Python Tutorial >How to Efficiently Divide a List into Balanced Chunks in Python?

How to Efficiently Divide a List into Balanced Chunks in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-28 19:33:10398browse

How to Efficiently Divide a List into Balanced Chunks in Python?

How to Divide a List into Balanced Portions

Dividing a list into equally-sized chunks is essential in various programming scenarios. Python provides several methods to accomplish this task, offering flexibility and efficiency. One popular approach utilizes a generator function.

The chunks() generator, introduced in the answer, allows you to partition a list into chunks of a specified size. It iterates over the list in steps of the defined chunk size, yielding consecutive chunks. The following code demonstrates how to use the chunks() generator:

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

To exemplify its functionality, consider splitting a list of integers into chunks of size 10:

import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))

This code produces the following output, showcasing the list divided into evenly-sized chunks:

[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [70, 71, 72, 73, 74]]

While the generator approach is recommended for its clarity and efficiency, Python also offers a concise list comprehension solution for list chunking:

[lst[i:i + n] for i in range(0, len(lst), n)]

Remember that using named functions like chunks() enhances code readability and maintainability.

The above is the detailed content of How to Efficiently Divide a List into Balanced Chunks in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn