DEV Community

Umesh
Umesh

Posted on

What is the difference between a for loop and an iterator in Python?

Iteraor and for loop doing that exact same thing just with a little change.

before going to explain, first let me clear about iterator waht it is....

Iterator:

Basically Iterator is an object that contains a countable number of values. It means having multiple values/ objects so we can use iterator to traverse all the values.

In Python, Iterator object having two mendatory methods iter() and next().

List, Tuples, Dictionary, Sets all are iterable objects and we can iterate and travese all the values.

For loop implements iterator in the background.
Before For loop starts, It will create iteratator object and iterator/ traverse all the elements until the StopIterator exception arise.

# get the iterator 
iterator_object = iter(some_iterable_object) 

while True: 
    try: 
        # get the next item         
        item = next(iterator_object) 
        # do whatever you need to do with this item 
    except StopIteration:   
        break

Enter fullscreen mode Exit fullscreen mode

So, For loop in nothing but an implementation of Iterator in an infinite while loop.

Top comments (0)