Skip to content

Instantly share code, notes, and snippets.

@patwooky
Last active October 6, 2022 03:34
Show Gist options
  • Save patwooky/ab12ae8e975b2fbd879654638b1e63d9 to your computer and use it in GitHub Desktop.
Save patwooky/ab12ae8e975b2fbd879654638b1e63d9 to your computer and use it in GitHub Desktop.
A short snippet that allows us to split a continuous list into sub-lists of N numbers
# a short snippet that allows us to split a continuous list into sub-lists of N numbers
def splitList(inList, subListSize):
'''
splits a continuous list into sub-lists of N numbers
inList - <list> a list of elements to split
subListSize - <int> the chunk size to split inList into
returns a list of sublists the size of subListSize
'''
a = list(range(12))
steps = subListSize
listOfN = []
for count in range(len(a)//steps):
# print(count)
listOfN.append(a[count*steps : (count*steps)+steps])
print(listOfN)
return listOfN
# sample runs
# note that any leftover elements in the list are truncated (ignored)
# list of 12 items split into chunks of 3
# in list is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(splitList(list(range(12)), 3))
# output:
# [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
# list of 12 items split into chunks of 4
# in list is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(splitList(list(range(12)), 4))
# output:
# [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
# list of 12 items split into chunks of 2
# in list is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(splitList(list(range(12)), 2))
# output:
# [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment