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

Here's a Python function that can divide a list into chunks of a specified size:

main.py
def chunk_list(lst, chunk_size):
    """
    This function takes a list and a chunk size as arguments
    and returns a list of lists, where each list has 'chunk_size'
    number of elements.
    """
    return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
273 chars
8 lines

This function uses list comprehension to split the list into chunks of size 'chunk_size' and returns a list of those chunks. Here's an example of how to use the function:

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

result = chunk_list(my_list, chunk_size)

print(result)
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
164 chars
8 lines

In this example, we have a list my_list and we want to split it into smaller lists of size 3, so we call the chunk_list function with my_list and chunk_size as arguments, and it returns a list of lists containing the desired chunks.

gistlibby LogSnag