Split a List Into Evenly Sized Chunks in Python

  • Post category:List

Splitting a list into evenly sized chunks in Python can be accomplished using list comprehension and the range() function. Here are two examples:

Example 1:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunk_size = 3
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]]

Example 2:

my_list = ['apple', 'banana', 'orange', 'kiwi', 'melon']
chunk_size = 2
chunks = [my_list[i:i+chunk_size] for i in range(0, len(my_list), chunk_size)]
print(chunks)

Output:

[[‘apple’, ‘banana’], [‘orange’, ‘kiwi’], [‘melon’]]