[Edu-sig] regarding 'iterables versus iterators' (example outbox, for peer review)

Kirby Urner kurner at oreillyschool.com
Fri Oct 11 01:46:49 CEST 2013


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20131010/e92c6d50/attachment.html>


More information about the Edu-sig mailing list