How to Split a list into N Parts in Python

To split a list into equal parts, use the array_split() function from the NumPy package – pass the original list as the first argument and the number to divide the list by as the second.

 

array_split() Syntax

 

np.array_split(list, sections_len, [axis=0])

 

Then iterate over each item in the newly created NumPy object and create Python lists from them.

 

Divide a List by Three in Python

To demonstrate this, let's split a list into three new lists and append them to another list.

 

import numpy as np

items = ["a", "b", "c", "d", "e", "f"]

split = np.array_split(items, 3)

split_items = []

for i in split:
   split_items.append(list(i))
   
print(split_items)
[['a', 'b'], ['c', 'd'], ['e', 'f']]

 

Split a List in Half in Python

Here is another example, this time splitting a list in half to create two new lists.

 

import numpy as np

items = ["a", "b", "c", "d", "e", "f"]

split = np.array_split(items, 2)

split_items = []

for i in split:
   split_items.append(list(i))
   
print(split_items)
[['a', 'b', 'c'], ['d', 'e', 'f']]

 

Splitting a List with Uneven Elements

If the original list can't be split evenly one or more of the new lists will not contain an equal number of elements.

 

import numpy as np

items = ["a", "b", "c", "d", "e", "f"]

split = np.array_split(items, 4)

split_items = []

for i in split:
   split_items.append(list(i))
   
print(split_items)
[['a', 'b'], ['c', 'd'], ['e'], ['f']]