Iterables and Iterators
Extract values one by one
iter() built-in to get iterator over iterable and use
next() to get elements one by one until
StopIteration is raised signifying the end:
Iterating over entire iterable
Iterator isn't reentrant!
Iterator vs Iterable vs Generator
An iterable is an object that can return an iterator. Any object with state that has an
__iter__ method and returns an iterator is an iterable. It may also be an object without state that implements a
__getitem__ method. - The method can take indices (starting from zero) and raise an
IndexError when the indices are no longer valid.
str class is an example of a
An Iterator is an object that produces the next value in a sequence when you call
next(*object*) on some object. Moreover, any object with a
__next__ method is an iterator. An iterator raises
StopIteration after exhausting the iterator and cannot be re-used at this point.
Iterable classes define an
__iter__ and a
__next__ method. Example of an iterable class :
Trying to instantiate the abstract class from the
collections module to better see this.
Handle Python 3 compatibility for iterable classes in Python 2 by doing the following:
Both of these are now iterators and can be looped through:
Generators are simple ways to create iterators. A generator is an iterator and an iterator is an iterable.
Verify only one element in iterable
Use unpacking to extract the first element and ensure it's the only one:
What can be iterable
Iterable can be anything for which items are received one by one, forward only. Built-in Python collections are iterable:
Generators return iterables: