Why is there no __iter__() for lists strings and tuples?

Manuel M. Garcia mgarcia at cole-switches.com
Fri Dec 20 17:23:35 EST 2002


On Fri, 20 Dec 2002 20:07:20 GMT, "Parzival Herzog"
<parz at shaw.SpamBucket.ca> wrote:
(edit)
>>>> x = 'abcdef'
>>>> x.__iter__()
>Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>AttributeError: 'str' object has no attribute '__iter__'

Strings, lists, tuples don't need an '__iter__' attribute because the
built in 'iter()' function handles them automatically.  You only need
the '__iter__' attribute in your user defined classes, because that is
where 'iter()' will look for it.

>>> s = 'ab'
>>> i = iter(s)
>>> i.next()
'a'
>>> i.next()
'b'
>>> i.next()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
StopIteration

Manuel



More information about the Python-list mailing list