Iteratoration question
andrew cooke
andrew at acooke.org
Thu Apr 2 21:32:41 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?
and the same is true when you use yield:
>>> def count():
... c = 0
... while c < 4:
... yield c
... c += 1
...
>>> for i in count(): print i
...
0
1
2
3
>>> x = count()
>>> dir(x)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__',
'__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__str__', 'close', 'gi_frame', 'gi_running',
'next', 'send', 'throw']
>>> i = x.__iter__()
>>> i.next()
0
>>> i.next()
1
andrew
More information about the Python-list
mailing list