create a function that splits a list into chunks in python in python

Here's an example of a function that splits a list into chunks of a specified size using slicing:

main.py
def chunkify(lst, size):
    """
    Splits a list into chunks of a specified size.

    Args:
        lst: The list to split.
        size: The size of each chunk.

    Returns:
        A list of chunks.
    """
    return [lst[i:i+size] for i in range(0, len(lst), size)]
274 chars
13 lines

This function takes in two arguments: the list to split (lst) and the size of each chunk (size). It then uses list comprehension and slicing to create a list of chunks.

Here's an example of using this function:

main.py
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
chunk_size = 3

chunks = chunkify(my_list, chunk_size)
print(chunks)
107 chars
6 lines

Output:

main.py
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
34 chars
2 lines

gistlibby LogSnag