Skip to content

Instantly share code, notes, and snippets.

@torbjo
Created July 5, 2018 12:33
Show Gist options
  • Save torbjo/6ed01b9bfa4441e11432d66d572680b9 to your computer and use it in GitHub Desktop.
Save torbjo/6ed01b9bfa4441e11432d66d572680b9 to your computer and use it in GitHub Desktop.
Split list/sequence in cunks of N elements
def split_n (seq, n=1, allow_partial=True):
if not allow_partial and (len(seq) % n != 0): raise RuntimeError()
return [seq[i:i+n] for i in range(0,len(seq),n)]
"""
>>> print (split_n ('abcdefghijklmnopqrstuvwxy', 4))
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx', 'y']
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment