Python Program to Split List into Chunks
[lst[i:i + n] for i in range(0, len(lst), n)], where lst is your list and n is the chunk size.Examples
How to Think About It
Algorithm
Code
def split_list_into_chunks(lst, n): return [lst[i:i + n] for i in range(0, len(lst), n)] # Example usage my_list = [1, 2, 3, 4, 5] chunk_size = 2 print(split_list_into_chunks(my_list, chunk_size))
Dry Run
Let's trace splitting the list [1, 2, 3, 4, 5] into chunks of size 2.
Start with i = 0
Take lst[0:2] which is [1, 2]
Next i = 2
Take lst[2:4] which is [3, 4]
Next i = 4
Take lst[4:6] which is [5]
| i | Chunk taken |
|---|---|
| 0 | [1, 2] |
| 2 | [3, 4] |
| 4 | [5] |
Why This Works
Step 1: Using range with step
The range(0, len(lst), n) generates start indexes for each chunk, moving forward by n each time.
Step 2: Slicing the list
Each slice lst[i:i+n] takes a sublist from index i up to but not including i+n, forming one chunk.
Step 3: Collecting chunks
All these slices are collected into a new list, which is the final list of chunks.
Alternative Approaches
def split_list_into_chunks(lst, n): chunks = [] for i in range(0, len(lst), n): chunks.append(lst[i:i+n]) return chunks print(split_list_into_chunks([1,2,3,4,5], 2))
from itertools import islice def split_list_into_chunks(lst, n): it = iter(lst) while True: chunk = list(islice(it, n)) if not chunk: break yield chunk print(list(split_list_into_chunks([1,2,3,4,5], 2)))
Complexity: O(n) time, O(n) space
Time Complexity
The code visits each element once to create chunks, so it runs in linear time relative to the list size.
Space Complexity
It creates a new list of chunks, so it uses extra space proportional to the input list size.
Which Approach is Fastest?
The list comprehension and for loop methods have similar speed; the generator method is more memory efficient but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| List comprehension | O(n) | O(n) | Simple and fast for most cases |
| For loop with append | O(n) | O(n) | Clear and beginner-friendly |
| Generator with itertools.islice | O(n) | O(k) where k is chunk size | Memory efficient for large lists |