Skip to content

Instantly share code, notes, and snippets.

@iKlotho
Last active March 21, 2022 14:37
Show Gist options
  • Save iKlotho/1329b409fcb401391285ee6202a41b87 to your computer and use it in GitHub Desktop.
Save iKlotho/1329b409fcb401391285ee6202a41b87 to your computer and use it in GitHub Desktop.
split given list to chunks most equally
def chunk_generator(chunks):
for chunk in chunks:
yield chunk
def split_to_chunks(paginate_list, chunk_size):
"""
It converts given list to mostly
equal sized arrays
"""
chunkcount = len(paginate_list) // chunk_size
chunk_list = []
remaining = []
for i in range(chunk_size):
lower, upper = i, i + 1
if lower == chunk_size - 1:
upper = len(paginate_list)
chunk = paginate_list[chunkcount * lower: chunkcount * upper]
if len(chunk) > chunkcount:
remaining.extend(chunk[chunkcount:])
chunk = chunk[:chunkcount]
chunk_list.append(chunk)
if remaining:
chunk = chunk_generator(chunk_list)
while remaining:
next(chunk).append(remaining.pop())
return chunk_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment