Alex Rivera | Logout

Split a list into parts based on a set of indexes in Python

Asked 2009-07-29T07:16:24.513
63

What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below

indexes = [5, 12, 17]
list = range(20)

return something like this

part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]

If there are no indexes it should return the entire list.

Edit
Report

2 Answers

0

This is all that I could think of

def partition(list_, indexes):
    if indexes[0] != 0:
        indexes = [0] + indexes
    if indexes[-1] != len(list_):
        indexes = indexes + [len(list_)]
    return [ list_[a:b] for (a,b) in zip(indexes[:-1], indexes[1:])]
answered 2009-07-29T07:32:07.927
-1

The plural of index is indices. Going for simplicity/readability.

indices = [5, 12, 17]
input = range(20)
output = []

for i in reversed(indices):
    output.append(input[i:])
    input[i:] = []
output.append(input)

while len(output):
    print output.pop()
answered 2009-07-29T07:43:52.397

Your Answer