Iteratoration question

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Apr 3 05:57:11 EDT 2009


On Thu, 02 Apr 2009 18:07:38 -0700, 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?

Not necessarily.

For loops will call __iter__ automatically if it exists, but that isn't 
the only way that for loops can work. There is an older sequence protocol 
that the for loop will use as well:

>>> class D(object):
...     def __getitem__(self, i):
...             if i < 5: return i
...             raise IndexError
...
>>> d = D()
>>> for i in d:
...     print i
...
0
1
2
3
4


-- 
Steven




More information about the Python-list mailing list