Python Forum

Full Version: Iterator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I cannot understand what is the purpose of iterators. Think
In other words, what are the benefits of using iterators (iter(), next(), etc) vs for example, looping with "for" statement?
As a beginner, I have some difficulty understanding these functions ( I am used to using for, while, loops)...
Thanks.
You use an iterator just like you do a list: with the for loop. You almost never want to call next() directly.

The main benefit to an iterator, is for things where calculating each item is expensive. For example, parsing every email in your mailbox could take a while, but if you use an iterator instead of a list, then you can do things like reading one email while the next one is being pre-rendered so it's nice and ready for you ahead of time.

Or for things where you don't know how many items there are (or there's an infinite number of them). A sequence of some sort, like the fibonacci numbers.

Or maybe you're reading data from a security camera... that's still turned on. You could wait forever for the camera to turn off, and then start working with the data, or you can use an iterator to consume the feed as you get it, without knowing how long that feed might last for.
One of the main benefits of iterators is precisely that they can be used in "for" statements. The iterator protocol, with the __iter__() and __next__() methods defines the minimal API that an object needs in order to become iterable.