0

While studying python programming I came across these concepts of iterators and generators. I understand that as I learn about programming language but what kind of actual use cases are there for these two terms.

Manan Jain
  • 27
  • 5
  • 3
    One frequent use-case is when you want to process (typically large) amounts of data incrementally and avoid needing to read it all into memory at once. Another is to implement coroutines. – martineau Aug 29 '21 at 05:59
  • 1
    Every time you do `for x in something` you are using an iterator. A generator is a type of iterator, generator functions with `yield` are a convenient language construct for writing iterators. The use-cases are endless, you see them *everywhere* in Python – juanpa.arrivillaga Aug 29 '21 at 06:18
  • @juanpa.arrivillaga so if one wants to use the `for x in something` and `return` something using `yield` then why was there a need to use iterators and generators. One can simply use loops and return statements instead Would that be a better option then? – Manan Jain Aug 29 '21 at 13:30
  • @martineau by co-routines you meant asynchronous execution of the code? – Manan Jain Aug 29 '21 at 13:32
  • 1
    Yes. It's a way to pass control (and data) back and forth between functions without `return` and is aka as non-preemptive multitasking. In other words, the classic meaning of the [term](https://en.wikipedia.org/wiki/Coroutine) — note the section on Python. – martineau Aug 29 '21 at 13:42
  • 1
    In a nutshell: they help your program efficiently scale, while at the same time providing delightful encapsulation patterns. More reading is going to help.. – Daniel Hao Aug 29 '21 at 15:52
  • @MananJain you aren't listening to me - **when you use loops you are using iterators**. Always. Python loops are iterator based for-loops – juanpa.arrivillaga Aug 29 '21 at 19:39

0 Answers0