How Do You Split a List into Evenly Sized Chunks?

Given a list of an unknown length, how can we divide the list into evenly sized chunks?

How Do You Split a List into Evenly Sized Chunks?
Photo by Mae Mu on Unsplash

The Challenge

Given a list of an unknown length, how can we divide the list into evenly sized chunks? Assuming that the list does not divide evenly to the specified chunk size, the remainder will be placed in the last chunk. For example, a list of 15 items being chunked into fours will have chunks of 4, 4, 4, and 3.

The Solution

Define a function that takes a list l and max chunk size n that returns a list lists where each nested list is n items long. We use the yield keyword to produce a generator, which will be more performant for long lists; however, as a result the function must be nested in a list to be printed.def even_chunks(l, n):
  for i in range(0, len(l), n):
     yield l[i:i + n]data = [3,4,5,2,3,4,3,5,6,7,2,3,4,5,4,7]
print(list(even_chunks(data,3)))
# [[3, 4, 5], [2, 3, 4], [3, 5, 6], [7, 2, 3], [4, 5, 4], [7]]

Honorable Mentions

List Comprehension: If you don’t want to mess with generators and the yield command, simple list comprehension can solve the challenge as well. Make sure to match variable names and chunk size accordingly.data = [3,4,5,2,3,4,3,5,6,7,2,3,4,5,4,7]
chunked_data = [
  data[i:i + 3]
  for i in range(0, len(data), 3)
]print(chunked_data)
# [[3, 4, 5], [2, 3, 4], [3, 5, 6], [7, 2, 3], [4, 5, 4], [7]]

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe