Iterator vs Iterable and working of FOR Loop. Let's Discuss!

Siddharth RaiSiddharth Rai
1 min read

Iterable:

It is an object, that one can iterate over. It generates an iterator when passed to iter() method.

Iterator:

An iterator is an object, which is used to iterate over an iterable object using next() method.

Note:

  • List object by default is not an iterator but an iterable.
  • While, string objects by default are iterable but not an iterator.

Let's have better clarity on the above concept with the help of the below example.

L = [1,2,3]    # declaring a variable
b = iter(L)    # making variable/object iterator
next(b) will yield '1'
next(b) will yield '2'
next(b) will yield '3'

Working of 'FOR Loop'

The best example to understand iterator and iterable is to learn how FOR Loop works. In FOR loop, it first makes the object iterable by calling function iter. Then it fires 'next' function until all elements are called. E.g.

Say 'a' is a string variable
a = 'Python'
S = iter(a)
next(S) will yield 'P'
next(S) will yield 'y'
next(S) will yield 't'
next(S) will yield 'h'
next(S) will yield 'o'
next(S) will yield 'n'
0
Subscribe to my newsletter

Read articles from Siddharth Rai directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Siddharth Rai
Siddharth Rai