Using much generalized way:
i = 0
final_list = []
flag = True
while flag:
temp_list = [index_list[i]]
while (i < len(index_list)-1) and (index_list[i+1] - index_list[i]==1):
i+=1
temp_list.append(index_list[i])
final_list.append(temp_list)
i+=1
if i >= len(index_list):
flag=False
print(final_list)
input : [3,4,8,9,35,36,37]
ouptut : [[3, 4], [8, 9], [35, 37]]
input : [1,3,5,7,9]
output : [[1, 1], [3, 3], [5, 5], [7, 7], [9, 9]]
Update:
new_list = []
for i, j in final_list:
new_list.append(list(range(i,j+1)))
print(new_list)
input: [3, 4, 5, 16, 17, 31, 32, 33, 34]
output : [[3, 4, 5], [16, 17], [31, 32, 33, 34]]