Iteratoration question

andrew cooke andrew at acooke.org
Thu Apr 2 21:29:24 EDT 2009


grocery_stocker wrote:
> 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?

yes!

in fact you can see them:

Python 2.5.4 (r254:67916, Mar 23 2009, 17:43:35)
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3,4]
>>> dir(l)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__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__',
'__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
>>> l.__iter__
<method-wrapper '__iter__' of list object at 0x7f5e61618c68>
>>> i = l.__iter__()
>>> dir(i)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__',
'__init__', '__iter__', '__length_hint__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'next']
>>> i.next()
1
>>> i.next()
2

note that the list only has __iter__, not next.  calling __iter__()
returns an iterator (something that has a next method) and calling next on
that gives you the same result.

dir() just shows all the attributes of an object.

andrew





More information about the Python-list mailing list