Algorithm


  1. Input:

    • lst: The input list to be split.
    • chunk_size: The size of each chunk.
  2. Validation:

    • Check if chunk_size is greater than 0. If not, raise a ValueError.
  3. Calculate Number of Chunks:

    • Calculate num_chunks using the formula: (len(lst) + chunk_size - 1) // chunk_size.
  4. Create Chunks:

    • Use list comprehension to create chunks by iterating over the range of num_chunks.
    • Each chunk is obtained using slicing: lst[i * chunk_size:(i + 1) * chunk_size].
  5. Output:

    • Return the list of chunks (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

x
+
cmd
[[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

x
+
cmd
[[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

x
+
cmd
[array([1, 2]), array([3, 4]), array([5, 6]), array([7, 8]), array([9])]
Advertisements

Demonstration


Python Programing Example to Split a List Into Evenly Sized Chunks-DevsEnv