August 2018
Intermediate to advanced
366 pages
10h 14m
English
The itertools.islice function is able to take a slice of any iterable. In our specific case, we want the slice that goes from the element we are looking for to the next one.
Once we have the slice containing the element we were looking for, we need to extract that item from the slice itself.
As islice acts on iterables, it returns an iterable itself. This means we can use next to consume it, and as the item we were looking for is actually the first of the slice, using next will properly return the item we were looking for.
In case the item is out of bounds (for example, we look for the fourth item out of just three), a StopIteration error is raised and we can trap it like we would for IndexError in normal lists.