Skip to content

Instantly share code, notes, and snippets.

@craigderington
Last active March 27, 2016 01:07
Show Gist options
  • Save craigderington/c368efec90e249771777 to your computer and use it in GitHub Desktop.
Save craigderington/c368efec90e249771777 to your computer and use it in GitHub Desktop.
Break a list into 'n' pieces. The last list may be larger than the rest if the list doesn't break cleanly.
#!/usr/bin/python
def partition(thelist, n):
try:
n = int(n)
list(thelist)
except (ValueError, TypeError):
return [thelist]
p = len(thelist) / n
return [thelist[p*i:p*(i+1)] for i in range(n - 1)] + [thelist[p*(i+1):]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment