1

I have a list of indices to exclude:

idx = [1, 3, 6]

and I want to automatically get 4 intervals/slices based on these indices, thanks to this post Split a list into parts based on a set of indexes in Python:

slices = [list[:1], list[2:3], list[4:6], list[7:]]

What is a pythonic way to do that?

** EDIT I solved it using a list comprehension and zip function:

'[list[i + 1: j] for i, j in zip([-1, *idx], [*idx, None])]
Filip Szczybura
  • 407
  • 5
  • 14
  • 1
    Please [edit] your question and add your attempt to do it. – martineau Apr 19 '21 at 20:42
  • 1
    @PranavHosangadi: The link question is not a duplicate (it doesn't create slices). – martineau Apr 19 '21 at 20:45
  • Filip, since you have solved it, you should post your solution as an answer. – Pranav Hosangadi Apr 19 '21 at 20:51
  • That solution might yield an empty list if 0 is to be excluded (`list[0:0] -> []`) , and an IndexOutOfRangeException if `len(list)-1` is to be excluded (`list[len(list):] -> IndexOutOfRangeException`). So I would not consider it a solution yet – Miguel Alorda Apr 19 '21 at 21:14

0 Answers0