Is there any Iterator type example?

DonQuixoteVonLaMancha at gmx.net DonQuixoteVonLaMancha at gmx.net
Tue Nov 15 17:42:14 EST 2005


How about this one:

import os
from os.path import join

def py_files(dir):
  for root, dirs, files in os.walk(dir):
    for name in files:
      if name.lower().endswith(".py"):
        yield join(root,name )

if __name__=="__main__":
  dir= "C:\\Python23\\"
  for f in py_files(dir):
    print f

In my opinion, iterators have two advantages:
1. They can make it easier to iterate over complicated structures, like
    a file tree in the above example.
2. Since they store only information on how to access the next item,
    they need often less memory. For example, map(f, list) creates a
new
    list [f(L) for L in list], while itertools.imap(f,list) creates an
iterator object.
    The iterator object often needs much less memory than the new list.

There was also a dicussion on this topic on the tutor list two days
ago, maybe you'd like to join.

Kind regards,
Karsten.

Thomas Moore schrieb:
> Hi:
> 
> Is there any example about how to use Iterator type?
> 
> --Thomas




More information about the Python-list mailing list