Iterable vs Iterator in Python

Let’s learn about iterables and iterators.

Indhumathy Chelliah
Analytics Vidhya

--

Photo by Jude Beck on Unsplash

Iterator

In Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__() . — python docs

  • An iterator is an object representing a stream of data.
  • It returns the data one element at a time.
  • A Python iterator must support a method called __next__() that takes no arguments and always returns the next element of the stream.
  • If there are no more elements in the stream,__next__() must raise the StopIteration exception.
  • Iterators don’t have to be finite.It’s perfectly reasonable to write an iterator that produces an infinite stream of data.

Iterable

In Python,Iterable is anything you can loop over with a for loop.

An object is called an iterable if u can get an iterator out of it.

  1. Calling iter() function on an iterable gives us an iterator.
  2. Calling next() function on iterator gives us the next element.
  3. If the iterator is exhausted(if it has no more elements), calling next() raises StopIteration exception.

--

--