Created
April 25, 2024 11:14
-
-
Save stephenchew/b3b4ffd4ccf9559de432c4118b6a770f to your computer and use it in GitHub Desktop.
O(1) way to chunk an array into small pieces in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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']] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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