Why is there no __iter__() for lists strings and tuples?
Oren Tirosh
oren-py-l at hishome.net
Sat Dec 21 03:45:30 EST 2002
On Fri, Dec 20, 2002 at 08:07:20PM +0000, Parzival Herzog wrote:
> >>> [1,2,3].__iter()__
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> AttributeError: 'list' object has no attribute '__iter__'
> >>>
>
> So is this a bug? Are strings, lists and tuples sequences? If they are, why
> is there no __iter__() attribute for them?
Prior to Python 2.2 iteration used __getitem__ and IndexError. Python 2.2
adds support for iterators using the __iter__ function but still supports the
older form of iteration. Since strings, lists and tuples work just fine with
the older form there was no need to support __iter__ for these types.
for i in a:
do_somewith_with(i)
is equivalent in Python < 2.2 to:
_tmpidx = 0
try:
while 1:
i = a[_tmpidx]
_tmpidx = _tmpidx +1
do_somewith_with(i)
except IndexError:
pass
and in Python >= 2.2:
if hasattr(a, '__iter__'):
_tmpiter = a.__iter__()
try:
while 1:
i = _tmpiter.next()
do_something_with(i)
except StopIteration:
pass
else:
# fall back to < 2.2 behavior
Oren
More information about the Python-list
mailing list