Skip to content

Instantly share code, notes, and snippets.

@stephenchew
Created April 25, 2024 11:14
Show Gist options
  • Select an option

  • Save stephenchew/b3b4ffd4ccf9559de432c4118b6a770f to your computer and use it in GitHub Desktop.

Select an option

Save stephenchew/b3b4ffd4ccf9559de432c4118b6a770f to your computer and use it in GitHub Desktop.
O(1) way to chunk an array into small pieces in Python
arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
chunk_three = chunk(arr, 3)
assert chunk_three == [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j"]]
chunk_default = chunk(arr)
assert chunk_default == [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j"]]
chunk_max = chunk(arr, 1000)
assert chunk_max == [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']]
from typing import TypeVar
T = TypeVar("T")
def chunk(array: list[T], size: int = 4) -> list[list[T]]:
return [
array[i * size : (i + 1) * size] for i in range((len(array) + size - 1) // size)
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment