Skip to content

Instantly share code, notes, and snippets.

@flashlin
Created April 16, 2021 01:17
Show Gist options
  • Save flashlin/e6f46f8f2f1c553d6dad38d1ca028833 to your computer and use it in GitHub Desktop.
Save flashlin/e6f46f8f2f1c553d6dad38d1ca028833 to your computer and use it in GitHub Desktop.
[Split a list into parts based on a set of indexes in Python] #python
indexes = [5, 12, 17]
list = range(20)
part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
from itertools import izip, chain
def partition(alist, indices):
pairs = izip(chain([0], indices), chain(indices, [None]))
return (alist[i:j] for i, j in pairs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment