Skip to content

Instantly share code, notes, and snippets.

@gboeer
Created March 7, 2024 13:22
Show Gist options
  • Save gboeer/f89ce5a769e24ddb4db1876aca456f70 to your computer and use it in GitHub Desktop.
Save gboeer/f89ce5a769e24ddb4db1876aca456f70 to your computer and use it in GitHub Desktop.
def array_chunks(arr, chunk_size):
"""
Splits an array into chunks of up to `chunk_size` elements.
Args:
arr (list): The input array to be split into chunks.
chunk_size (int): The size of each chunk. The last chunk may be smaller if there are not enough elements left.
Returns:
list of lists: A list where each element is a chunk of the original array, up to `chunk_size` in length.
Examples:
>>> split_array_into_chunks([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]
>>> split_array_into_chunks([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> split_array_into_chunks([1, 2, 3, 4, 5, 6], 1)
[[1], [2], [3], [4], [5], [6]]
>>> split_array_into_chunks([1, 2, 3, 4, 5, 6], 7)
[[1, 2, 3, 4, 5, 6]]
"""
return [arr[i:i + chunk_size] for i in range(0, len(arr), chunk_size)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment