What is the difference between an iterator and an iterable? ---
I will try to be concise: an iterator has a __next__ method for "inch worming" forward (from yield to yield internally, if defined by a generator function, but only some iterators are). Iterables, if they have an __iter__ method, should give rise to an iterator by that method. However, even something so dumb as a class with just __getitem__ can be treated as an iterable. Let's see: class Dumb: """uber primitive""" def __init__(self, it): self.thelist = it def __getitem__(self, n): return self.thelist[n] obj = Dumb(list("mary had a little lamb")) for d in obj: # iterables will work here print(d, end="") print() # can we use it with iter() ? theiter = iter(obj) if "__next__" in dir(theiter): print("wow, we have a grown up iterator!") for i in range(4): print(next(theiter)) Output: mary had a little lamb wow, we have a grown up iterator! m a r y === Kirby Urner Senior Python Mentor Python Track / OST
_______________________________________________ Edu-sig mailing list Edu-sig@python.org https://mail.python.org/mailman/listinfo/edu-sig