Why do we learn iterators and generators after arrays, lists, etc?

I have struggled wrapping my brain around iterators and generators (Python, JavaScript). I think I finally have something approaching a useful understanding of them, which I elaborate succinctly below, and now I wonder why the more basic objects and methods of iterators aren't presented earlier than the more specific lists and arrays. Any thoughts? Iterators are a class that define methods for accessing and traversing (passing from one element to another) data and create instances that are "iterable". Generators are a subclass of iterators that create an iterable generator object by calling "yield" in a function. Lists and arrays are classes of containers that inherit, adapt and extend the Iterator methods.

8/23/2019 3:51:50 PM

David Crowley

7 Answers

New Answer


I don't know. Maybe because iterators iterate over lists etc., unless you define what a list is, you can't explain well what iterators are iterating over maybe?


Iterators are not iterable. They provide methods to iterate over an iterable. And lists and arrays usually don't have iterator methods (at least not in Python).


"in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__()" --quoted from w3schools Iterators are custom objects hence they represent a more advanced topic that involves OOP and the implementation of magic methods. Generators are bringing in tools from functional programming (lazy sequences). Arrays / lists are really the most basic data structures that can be found in all programming languages, and probably the easiest way to explain the usefulness of for/while loops to a beginner. I think that is enough reason to learn them first.


David Crowley I think you are right. The teaching order maybe related to ease of understanding and/or the order of addition of the concepts to the language.


True. But they are also called and created in for loops. It seems to be something quite fundamental to how programming languages work. Perhaps it's just too abstract for introductory material where you do want to describe things that are easy for the learner to visualize/relate to.


Iterators are classes, while generators are functions. Tibor Santa to clarify: both are "lazy". It is just the way they handle the state. Iterators keep the state inside them as any other Object in OOP would. A call of __next__() changes the state. Generators are stateful functions, or "lazy". They are indeed special, as they use the yield keyword. Yield creates a generator from a function. That way a functions execution is set on hold, once the value is returned and will continue once the generator is called again. Think of it as an iterator, but wihout all the ugly OOP stuff. https://code.sololearn.com/c4WvQ17t99bi/?ref=app


I thought generators are more memory friendly.