Iterable and Iterator

All iterators are iterables but all iterables are not iterators !! It is really very confusing.

Let me demostrate with example :

for i in ‘Python’:


Above code can be represented as

for <var> in <iterable>:


So, what are they ? Where are they used ?

Iterables and Iterators used __iter__() functions however Iterator use __next__() function to iterate on the Iterables


How for loop works in python:

Flow diagram of For Loop

Iterable calls Iter function that returns iterator . The Iterator instance calls next function for each element.

If the exception “StopIteration” is raised the next() function call is stopped. Finally loop stops.

For details Please read PEP 234

Leave a Comment

Your email address will not be published.