Algorithm
-
Input:
lst
: The input list to be split.chunk_size
: The size of each chunk.
-
Validation:
- Check if
chunk_size
is greater than 0. If not, raise aValueError
.
- Check if
-
Calculate Number of Chunks:
- Calculate
num_chunks
using the formula:(len(lst) + chunk_size - 1) // chunk_size
.
- Calculate
-
Create Chunks:
- Use list comprehension to create
chunks
by iterating over the range ofnum_chunks
. - Each chunk is obtained using slicing:
lst[i * chunk_size:(i + 1) * chunk_size]
.
- Use list comprehension to create
-
Output:
- Return the list of chunks (
chunks
).
- Return the list of chunks (
Code Examples
#1 Code Example- Python Programing Using yield
Code -
Python Programming
def split(list_a, chunk_size):
for i in range(0, len(list_a), chunk_size):
yield list_a[i:i + chunk_size]
chunk_size = 2
my_list = [1,2,3,4,5,6,7,8,9]
print(list(split(my_list, chunk_size)))
Copy The Code &
Try With Live Editor
Output
[[1, 2], [3, 4], [5, 6], [7, 8], [9]]
#2 Code Example with Python Programming
Code -
Python Programming
chunk_size = 2
list_chunked = [my_list[i:i + chunk_size] for i in range(0, len(my_list), chunk_size)]
print(list_chunked)
Copy The Code &
Try With Live Editor
Output
[[1, 2], [3, 4], [5, 6], [7, 8], [9]]
#3 Code Example- Python Programing Using numpy
Code -
Python Programming
import numpy as np
my_list = [1,2,3,4,5,6,7,8,9]
print(np.array_split(my_list, 5))
Copy The Code &
Try With Live Editor
Output
[array([1, 2]), array([3, 4]), array([5, 6]), array([7, 8]), array([9])]
Demonstration
Python Programing Example to Split a List Into Evenly Sized Chunks-DevsEnv