Iterator / Iteratable confusion

Scott David Daniels Scott.Daniels at Acm.Org
Mon Feb 14 17:23:07 EST 2005


Francis Girard wrote:
> Le dimanche 13 Février 2005 23:58, Terry Reedy a écrit :
>>Iterators are a subgroup of iterables.  Being able to say iter(it) without
>>having to worry about whether 'it' is just an iterable or already an
>>iterator is one of the nice features of the new iteration design.
> 
> I have difficulties to represent an iterator as a subspecie of an iteratable 
> ... One of the result of not distinguishing them is that, at some point in
> your programming, you are not sure anymore if you have an iterator or an 
> iteratable ; and you might very well end up calling "iter()" or "__iter__()" 
> everywhere.

The point is _almost_, but not exactly unlike that.
Because the "for ... in ..." construct calls iter itself, you seldom
need (as a code user) to distinguish between iterators and iterables.
However, there will come a day when you see some code like:

     first = True
     for blunge in whatever:
         if first:
             first = False
         else:
             print 'and',
         print blunge

And you think, "I can make that clearer," so you write:

     source = iter(whatever)
     print source.next()
     for blunge in source:
         print 'and', blunge

Because of how iterables work, you know you can do this locally
without looking all around to see what "whatever" is.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list