How To Split a list into equally sized chunks in Python

Created
Modified

Using List Comprehension

List comprehensions provide a concise way to create lists. The following example:

#!/usr/bin/python3
# -*- coding: utf8 -*-

# initialize
lst = ['a'] * 7

# chunks
n = 3

a = [lst[i:i+n] for i in range(0, len(lst), n)]
print(a)
[['a', 'a', 'a'], ['a', 'a', 'a'], ['a']]

Using yield

The yield keyword enables a function to comeback where it left off when it is called again. For example,

#!/usr/bin/python3
# -*- coding: utf8 -*-

def chunks(l, n):
  for i in range(0, len(l), n):
    yield l[i:i+n]

# initialize
lst = ['a'] * 7

# chunks
n = 3

a = list(chunks(lst, n))
print(a)
[['a', 'a', 'a'], ['a', 'a', 'a'], ['a']]

Using NumPy Module

NumPy is the fundamental package for scientific computing in Python.

If you use pip, you can install NumPy with:

pip
pip install numpy
pip3 install numpy
#!/usr/bin/python3
# -*- coding: utf8 -*-

# Import module
import numpy as np

# initialize
lst = ['a'] * 7

a = np.array_split(lst, 3)
print(a)
[['a' 'a' 'a'],['a' 'a'],['a' 'a']]

numpy.array_split split an array into multiple sub-arrays. For an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n.

Related Tags

#split# #list# #chunks#