How to Split a List into Chunks in Python?

Estimated read time 2 min read

To split a list into chunks of a specific size in Python, you can use a loop or a list comprehension with slicing. Here’s an example using a loop:

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

# Split the list into chunks of a specific size
chunks = []
for i in range(0, len(my_list), chunk_size):
    chunks.append(my_list[i:i+chunk_size])

print(chunks)  # Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In this example, we define a list my_list and a variable chunk_size that specifies the size of each chunk. We use a for loop to iterate over the indices of the list, and use slicing to extract each chunk from the original list. The range() function generates a sequence of indices that we use with slicing to extract each chunk.

Alternatively, you can use a list comprehension with slicing:

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

# Split the list into chunks of a specific size
chunks = [my_list[i:i+chunk_size] for i in range(0, len(my_list), chunk_size)]

print(chunks)  # Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In this example, we use a list comprehension to split the list into chunks of the specified size. The range() function generates a sequence of indices that we use with slicing to extract each chunk from the original list.

Either method should work for splitting a list into chunks of a specific size in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply