SoFunction
Updated on 2024-11-15

Python implementation of splitting a list into blocks of size N

Method 1: Use yield

The yield keyword enables a function to return to where it stopped when it is called again. This is a key difference from a regular function, which can't go back to where it stopped. the yield keyword helps the function remember its state. yield enables the function to hang and resume, and it returns a value when it hangs to execute.

my_list = ['geeks', 'for', 'geeks', 'like',
           'geeky','nerdy', 'geek', 'love',
               'questions','words', 'life']
# Yield successive n-sized
# chunks from l.
def divide_chunks(l, n):
    # looping till length l
    for i in range(0, len(l), n): 
        yield l[i:i + n]
# How many elements each
# list should have
n = 5
x = list(divide_chunks(my_list, n))
print (x)

exports

[['geeks', 'for', 'geeks', 'like', 'geeky'], 
 ['nerdy', 'geek', 'love', 'questions', 'words'], 
 ['life']]

Method 2: Use a for loop

In this example, we use loops and list slicing in Python, which will help us break the list into chunks.

my_list = [1, 2, 3, 4, 5,
           6, 7, 8, 9]
start = 0
end = len(my_list)
step = 3
for i in range(start, end, step):
    x = i
    print(my_list[x:x+step])

exports

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Method 3: Use list parsing

In Python, splitting lists into one line of code and splitting lists into multiple lists is an elegant way to do this.

my_list = [1, 2, 3, 4, 5,
              6, 7, 8, 9]
# How many elements each
# list should have
n = 4 
# using list comprehension
final = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )] 
print (final)

exports

[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

Another realization:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
# How many elements each 
# list should have 
n = 4
# using list comprehension 
x = [l[i:i + n] for i in range(0, len(l), n)] 
print(x)

exports

[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

Method 4: Using Numpy

Here, we use Numpy.array_split, which splits the array into n equal-sized chunks.

import numpy as np
arr = range(30)
np.array_split(arr, 6)

exports

[array([0, 1, 2, 3, 4]),
 array([5, 6, 7, 8, 9]),
 array([10, 11, 12, 13, 14]),
 array([15, 16, 17, 18, 19]),
 array([20, 21, 22, 23, 24]),
 array([25, 26, 27, 28, 29])]

Method 5: Using itertools

from itertools import islice
def chunk(arr_range, arr_size):
    arr_range = iter(arr_range)
    return iter(lambda: tuple(islice(arr_range, arr_size)), ())
print(list(chunk(range(30), 5)))

exports

[(0, 1, 2, 3, 4),
 (5, 6, 7, 8, 9),
 (10, 11, 12, 13, 14),
 (15, 16, 17, 18, 19),
 (20, 21, 22, 23, 24),
 (25, 26, 27, 28, 29)]

Method 6: Using Collections

from collections import deque
def split_list(input_list, chunk_size):
  # Create a deque object from the input list
  deque_obj = deque(input_list)
  # While the deque object is not empty
  while deque_obj:
      # Pop chunk_size elements from the left side of the deque object
      # and append them to the chunk list
      chunk = []
      for _ in range(chunk_size):
        if deque_obj:
          (deque_obj.popleft())
      # Yield the chunk
      yield chunk
input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunk_size = 3
chunks = list(split_list(input_list, chunk_size))
print(chunks) 

exports

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

The deque class allows you to easily split a list into blocks of a specific size by easily removing elements from the left or right side of the list. The code uses a while loop and a generator function to iterate through the list, generating one block at a time. The loop breaks when the deque is empty, which indicates that all elements have been processed.

Method 7: Partial assignment

Here's an example of a block list of size N that you can easily work with:

my_list = list(range(10))
chunk_size = 3
while my_list:
    chunk, my_list = my_list[:chunk_size], my_list[chunk_size:]
    print(chunk)

exports

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]

to this article on the Python implementation of the list will be split into blocks of size N is introduced to this article, more related Python split list content, please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!