[Tutor] iteritems() vs items()

Kent Johnson kent37 at tds.net
Mon Nov 14 00:39:51 CET 2005


Tim Johnson wrote:
> * Liam Clarke-Hutchinson <Liam.Clarke-Hutchinson at business.govt.nz> [051113 12:41]:
> 
>>Someone correct me if I'm wrong, but I believe there is no specific iterator
>>object, but rather objects that have a method for __iter___...
> 
>  
>   Some light is slowly dawning here (I think) .... from 
>   http://docs.python.org/ref/yield.html
> 
>   It appears that a generator, is an object, but
>   not derived from a class, but from a generator function,
>   using yield.

I would say it is an object of a built-in class created by calling a generator function, which is a function that uses yield.

You can create your own iterators by defining a class that defines the special methods __iter__() and next(). __iter__ just returs self, and next() returns the next item in the iteration or raises StopIteration. See
http://docs.python.org/lib/typeiter.html

Generators provide a convenient short-cut for creating many kinds of iterators because generator state is maintained implicitly. For example, a class for iterators that count from 1 to 10 might look like this:

class counter:
  def __init__(self):
    self.count = 0
  def __iter__(self):
    return self
  def next(self):
    if self.count < 10:
      self.count += 1
      return self.count
    raise StopIteration

The equivalent generator function could be

def counter():
  for count in range(1, 11):
    yield count

or, maybe a fairer comparison would be

def counter():
  count = 0
  if count < 10:
    count += 1
    yield count

which is still much shorter and easier to understand than the class version. Usage of all three is identical:

for i in counter():
  print i

Kent



More information about the Tutor mailing list