Update May 2023: Option 'fine' integrated.
Update Apr. 2023: Thank you Donna for your comment! I did some changes, like you suggested, but i think that it's a pretty easy example to have more precise information how it works.
The 'slieced' function is maybe a better solution for very long sequencies then the others i saw 'cause you slice the rest of the sequence not the whole again.
It's better to use Sequence_T instead of Sequence 'cause later you can complement the variables with proper commands depending of the sequence-types 'list' or 'tuple' (E.g.: append to a list)
from collections.abc import Sequence
from typing import Iterable, TypeVar
Sequence_T = TypeVar('Sequence_T', bound=Sequence)
def cut(seq: Sequence_T, index: int) -> tuple[Sequence_T, Sequence_T]:
""" Cut in two slieces. Works with minus-index as well. """
return seq[:index], seq[index:]
def sliced(seq: Sequence_T, indexes: Iterable[int], fine=False) -> list[Sequence_T]:
"""
Works like cut in two, but this can sliece the sequence multiple times.
If you wanna fine sliecies, turn fine=True.
Then one slice will appear not in a sequence any more.
Take care of the maximum length of sequence that no empty sequences appear inside the result.
"""
def checked(a_seq: Sequence_T):
return a_seq[0] if len(a_seq) == 1 else a_seq
def as_it_is(a_seq: Sequence_T):
return a_seq
if fine:
f = checked
else:
f = as_it_is
previous_i = 0
result = []
for i in indexes:
seq2 = cut(seq, i-previous_i)
result.append(f(seq2[0]))
seq = seq2[1]
previous_i = i
result.append(f(seq))
return result
t = (1, 2, 3, 4, 5)
print(cut(t, 3)) # Output: ((1, 2, 3), (4, 5))
print(sliced(t, (-3,-2))) # Output: [(1, 2), (3,), (4, 5)]
print(sliced(t, (2,3))) # Output: [(1, 2), (3,), (4, 5)]
print(sliced(t, (2,3), True)) # Output: [(1, 2), 3, (4, 5)]
print(sliced(t, t[:-1], True)) # Output: [1, 2, 3, 4, 5]
print(sliced(t, cut(t, -1)[0], True)) # Output: [1, 2, 3, 4, 5]
print(sliced(t, t, True)) # No good output: [1, 2, 3, 4, 5, ()]