[Tutor] Iterators and Generators...

Gregor Lingl glingl at aon.at
Wed Aug 13 18:56:45 EDT 2003


Neil Schemenauer schrieb:

>Marc Barry wrote:
>  
>
>>I have a class which is an iterator, but I can't figure out why it is not 
>>working.
>>    
>>
>
>This is probably what you want:
>
>    class list_iterator:
>
>            def __init__(self, a_list):
>                    self.a_list = a_list
>
>            def __iter__(self):
>                    for i in self.a_list:
>                            yield i
>  
>

Doesn't this one do exactly the same (without using classes):

 >>> def list_iterator(a_list):
    for item in a_list:
        yield item

       
 >>> li = list_iterator([1,2,3])
 >>> li.next()
1
 >>> while 1:
    try:
              print li.next()
        except:
              break

2
3

Reagards, Gregor

>A function containing a 'yield' statement returns a generator when it is
>called.  Calling '.next()' on that generator object starts executation
>of the function body until a yield statement is reached (and so on).  If
>the end of the function is reached then StopIteration is raised.
>
>HTH,
>
>  Neil
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>







More information about the Tutor mailing list