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.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay