Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How it works...

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content