From dfbc535c8b67571aaf65fe90a8d7fd992f0d0e38 Mon Sep 17 00:00:00 2001 From: Tithi Joshi Date: Thu, 12 Feb 2026 11:09:51 +0530 Subject: [PATCH] Improve split_list with type hints, validation, and docstring The function now includes type hints and a detailed docstring explaining its parameters, return value, and potential exceptions. --- python-list/chunks.py | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/python-list/chunks.py b/python-list/chunks.py index 0f7a1607fd..435349368b 100644 --- a/python-list/chunks.py +++ b/python-list/chunks.py @@ -1,6 +1,28 @@ -def split_list(list_object, chunk_size): - chunks = [] - for start in range(0, len(list_object), chunk_size): - stop = start + chunk_size - chunks.append(list_object[start:stop]) - return chunks +from typing import Any, List + + +def split_list(list_object: List[Any], chunk_size: int) -> List[List[Any]]: + """ + Split a list into smaller chunks of a given size. + + Args: + list_object: The list to split. + chunk_size: The size of each chunk (must be a positive integer). + + Returns: + A list of sublists, each with at most `chunk_size` elements. + + Raises: + ValueError: If chunk_size is less than or equal to zero. + + Example: + >>> split_list([1, 2, 3, 4, 5], 2) + [[1, 2], [3, 4], [5]] + """ + if chunk_size <= 0: + raise ValueError("chunk_size must be a positive integer") + + return [ + list_object[start : start + chunk_size] + for start in range(0, len(list_object), chunk_size) + ]