Skip to content

Commit dfbc535

Browse files
authored
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.
1 parent ac9079d commit dfbc535

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

python-list/chunks.py

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,28 @@
1-
def split_list(list_object, chunk_size):
2-
chunks = []
3-
for start in range(0, len(list_object), chunk_size):
4-
stop = start + chunk_size
5-
chunks.append(list_object[start:stop])
6-
return chunks
1+
from typing import Any, List
2+
3+
4+
def split_list(list_object: List[Any], chunk_size: int) -> List[List[Any]]:
5+
"""
6+
Split a list into smaller chunks of a given size.
7+
8+
Args:
9+
list_object: The list to split.
10+
chunk_size: The size of each chunk (must be a positive integer).
11+
12+
Returns:
13+
A list of sublists, each with at most `chunk_size` elements.
14+
15+
Raises:
16+
ValueError: If chunk_size is less than or equal to zero.
17+
18+
Example:
19+
>>> split_list([1, 2, 3, 4, 5], 2)
20+
[[1, 2], [3, 4], [5]]
21+
"""
22+
if chunk_size <= 0:
23+
raise ValueError("chunk_size must be a positive integer")
24+
25+
return [
26+
list_object[start : start + chunk_size]
27+
for start in range(0, len(list_object), chunk_size)
28+
]

0 commit comments

Comments
 (0)