Iteratoration question

MRAB google at mrabarnett.plus.com
Thu Apr 2 21:39:04 EDT 2009


grocery_stocker wrote:
> On Apr 2, 4:41 pm, "andrew cooke" <and... at acooke.org> wrote:
>> Robert Kern wrote:
>>>> replace return with yield and it might work.
>>>> i have to go eat, but if it doesn't read the python docs on iterators -
>>>> for examplehttp://docs.python.org/reference/expressions.html#index-1825
>>> No, .next() needs to be a regular function that returns a value. What he
>>> needs
>>> is an __iter__() method that returns self. Alternately, __iter__ could be
>> yeah, sorry, i was in a rush and not thinking straight.  andrew
> 
> Okay, I was thinking more about this. I think this is also what is
> irking me. Say I have the following..
> 
>>>> a = [1,2,3,4]
>>>> for x in a:
> ...     print x
> ...
> 1
> 2
> 3
> 4
> 
> Would 'a' somehow call __iter__ and next()? If so, does python just
> perform this magically?
> 
The for loop calls the __iter__() method to get an iterator object and
then calls the next() method of the iterator object repeatedly to get
the values.

Sometimes you want to give an existing iterator to the for loop; for
that reason iterator objects (can) have an __iter__() method which just
returns the object itself.

For example:

The 'list' class has the __iter__() method:

 >>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append',
'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']

The __iter__() method returns a 'listiterator' instance:

 >>> i = iter([])
 >>> type(i)
<type 'listiterator'>

The 'listiterator' class also has the __iter__() method:

 >>> dir(i)
['__class__', '__delattr__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__iter__',
'__length_hint__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next']

which just returns itself:

 >>> iter(i) is i
True



More information about the Python-list mailing list