0

An iterable and a generator in Python have a similar behavior, but a generator is much simpler to write use - it is only a single function, vs. a class with several methods __iter__ and __next__. Is there a use-case when using an iterable class is better?

Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183
  • Iterators have more flexibility. Take a look at the `range` class, for example. – Barmar Mar 01 '22 at 18:40
  • 1
    E.g. you can use `if x in range(1, 10):`, you can't do that with a generator. – Barmar Mar 01 '22 at 18:41
  • 1
    @Barmar why couldn't you do that? `b = (x for x in range(10))` `print(2 in b)` – Eli Harold Mar 01 '22 at 18:42
  • @EliHarold Better example: `x in range(100000000000)`. The generator has to do all the looping, the `__in__` method can test it efficiently. – Barmar Mar 01 '22 at 18:46
  • @Barmar good point, but isn't that speed rather than flexibility? Not trying to be difficult, just trying to learn also. This is an interesting question to me. – Eli Harold Mar 01 '22 at 18:48
  • @EliHarold When I wrote my comment I didn't realize you could do that.... – Barmar Mar 01 '22 at 18:49
  • I see, couldn't you also just do `if x > botOfRnange and x < topOfRange:` (which is what I believe `range()` does anyway) instead of using range or a generator to be quick and explicit? – Eli Harold Mar 01 '22 at 18:51
  • Generators **are iterators**. Generator functions are convenient ways to create iterators. – juanpa.arrivillaga Mar 01 '22 at 19:14
  • @Barmar `range` is not an iterator. – juanpa.arrivillaga Mar 01 '22 at 19:15
  • 1
    @EliHarold not exactly, because `range` supports a step, but basically – juanpa.arrivillaga Mar 01 '22 at 19:17
  • @juanpa.arrivillaga ahh true. – Eli Harold Mar 01 '22 at 19:18
  • 2
    You are conflating *iterables* with iterators in your question, which seems to be specifically about iterators. An *iterable* is any object that has an `__iter__` method, and *iterator* has an `__iter__` method that simply does `return self`, but also has a `__next__` method. Containers (lists, dicts, etc) are generally *iterable* but not iterators. All iterators are iterable, of course. – juanpa.arrivillaga Mar 01 '22 at 19:22

0 Answers0