How do you split a list into n parts in python?

Sometimes, we want to split a list into N parts of approximately equal length with Python.

In this article, we’ll look at how to split a list into N parts of approximately equal length with Python.

How to split a list into N parts of approximately equal length with Python?

To split a list into N parts of approximately equal length with Python, we can use list comprehension.

For instance, we write:

def chunkify(lst, n):
    return [lst[i::n] for i in range(n)]


chunks = chunkify(list(range(13)), 3)
print(chunks)

We define the chunkify function to split the lst list into n chunks.

To do this, we use list comprehension to return slices of list with from index i to the end with n items in each chunk.

Then we call chunkify with the list(range(13)) list and 3 to divide the list into 3 chunks.

Therefore, chunks is [[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]].

Conclusion

To split a list into N parts of approximately equal length with Python, we can use list comprehension.

Web developer specializing in React, Vue, and front end development.

View Archive

In this example, you will learn to split a list into evenly sized chunks in different ways.

To understand this example, you should have the knowledge of the following Python programming topics:

  • Python List
  • Python Generators

Example 1: Using yield

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)))

Output

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

In the above example, we have defined a function to split the list.

  • Using a for loop and range() method, iterate from 0 to the length of the list with the size of chunk as the step.
  • Return the chunks using yield. list_a[i:i+chunk_size] gives each chunk. For example, when i = 0, the items included in the chunk are i to i + chunk_size which is 0 to (0 + 2)th index. In the next iteration, the items included are 2 to 2 + 2 = 4.

Learn more about yield at Python Generators.

You can do the same thing using list compression as below.

chunk_size = 2
list_chunked = [my_list[i:i + chunk_size] for i in range(0, len(my_list), chunk_size)]
print(list_chunked)

Output

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

Learn more about list comprehension at Python List Comprehension.


Example 2: Using numpy

import numpy as np

my_list = [1,2,3,4,5,6,7,8,9]
print(np.array_split(my_list, 5))

Output

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

array_split() is a numpy method that splits a list into equal sized chunks. Here, the number of chunks is 5.

Note: You need to install numpy on your system.

A list can be split based on the size of the chunk defined. Splitting a list into n parts returns a list of n lists containing an equal number of list elements. If the number of lists, n, does not evenly divide into the length of the list being split, then some lists will have one more element than others.

Let’s traditionally split the list.

To split a list in Python, call the len(iterable) method with iterable as a list to find its length and then floor divide the length by 2 using the // operator to find the middle_index of the list.

list = [11, 18, 19, 21]

length = len(list)

middle_index = length // 2

first_half = list[:middle_index]
second_half = list[middle_index:]

print(first_half)
print(second_half)

Output

[11, 18]
[19, 21]

As you can see from the output, we split the list in the exact half. We used the colon operator(:) to access the first and second half of the split list.

How to split a list into n parts in Python

To split a list into n parts in Python, use the numpy.array_split() function. The np.split() function splits the array into multiple sub-arrays.

The numpy array_split() method returns the list of n Numpy arrays, each containing approximately the same number of elements from the list.

import numpy as np

listA = [11, 18, 19, 21, 29, 46]

splits = np.array_split(listA, 3)

for array in splits:
    print(list(array))

Output

[11, 18]
[19, 21]
[29, 46]

In this example, we split the list into 3 parts.

Split a List Into Even Chunks of N Elements in Python

A list can be split based on the size of the chunk defined. This means that we can determine the size of the chunk. If the subset of a list doesn’t fit in the size of the defined chunk, fillers need to be inserted in the place of the empty element holders. We will be using None as filters to fill in those empty element holders.

def list_split(listA, n):
    for x in range(0, len(listA), n):
        every_chunk = listA[x: n+x]

        if len(every_chunk) < n:
            every_chunk = every_chunk + \
                [None for y in range(n-len(every_chunk))]
        yield every_chunk


print(list(list_split([11, 21, 31, 41, 51, 61, 71, 81, 91, 101, 111, 112, 113], 7)))

Output

[[11, 21, 31, 41, 51, 61, 71], [81, 91, 101, 111, 112, 113, None]]

The list has been split into equal chunks of 7 elements each.

The above list_split() function takes the arguments: listA for the list and chunk_size for a number to split it by. Then, the function iterates through the list with an increment of the chunk size n.

Each chunk is expected to have the size given as an argument. If there aren’t enough elements to split the same size, the remaining unused elements are filled with None.

That is it for splitting a list in Python.

See also

Split string with multiple parameters

Split line in Python

Python String rsplit()

Python String splitlines()

How do you split a list into equal parts in Python?

Python Program to Split a List Into Evenly Sized Chunks.
Using a for loop and range() method, iterate from 0 to the length of the list with the size of chunk as the step..
Return the chunks using yield . list_a[i:i+chunk_size] gives each chunk..

How do you split data in a list in Python?

Python String split() Method The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you divide an array into N equal parts in Python?

python divide array into n parts.
def split(a, n):.
k, m = divmod(len(a), n).
return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)).
print( list(split(range(11), 3)) ) # [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]].

How do you split a list into multiple lists in Python?

Split Python Lists into Chunks Using a List Comprehension.
We declare a variable chunk_size to determine how big we want our chunked lists to be..
For our list comprehensions expression, we index our list based on the ith to the i+chunk_sizeth position..