Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Iterator
#1
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.
Reply
#2
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.
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  prime numbers with iterator and generator cametan_001 8 1,926 Dec-17-2022, 02:41 PM
Last Post: cametan_001
  resetting an iterator to full Skaperen 7 7,063 Feb-20-2022, 11:11 PM
Last Post: Skaperen
  popping an iterator Skaperen 11 3,757 Oct-03-2021, 05:08 PM
Last Post: Skaperen
  q re glob.iglob iterator and close jimr 2 2,265 Aug-23-2021, 10:14 PM
Last Post: perfringo
  Problem with an iterator grimm1111 9 4,381 Feb-06-2021, 09:22 PM
Last Post: grimm1111
  Multi-class iterator Pedroski55 2 2,410 Jan-02-2021, 12:29 AM
Last Post: Pedroski55
  is a str object a valid iterator? Skaperen 6 5,683 Jan-27-2020, 08:44 PM
Last Post: Skaperen
  discard one from an iterator Skaperen 1 2,009 Dec-29-2019, 11:02 PM
Last Post: ichabod801
  how do i pass duplicates in my range iterator? pseudo 3 2,389 Dec-18-2019, 03:01 PM
Last Post: ichabod801
  looking for a sprcil iterator Skaperen 7 3,397 Jun-13-2019, 01:40 AM
Last Post: Clunk_Head

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020