Why don't python strings have an __iter__ method?

Question:

How is it that we can iterate over python strings when strings don’t provide an __iter__ method?

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "asdf".__iter__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__iter__'
>>> it = iter("asdf")      
>>> it
<iterator object at 0xb736f5ac>
>>> 

My understanding from the documentation is that an __iter__ method is required for iteration. Why don’t Python strings follow the same convention, and how do they provide iteration without doing so?

Asked By: Alexander Bird

||

Answers:

From your link:

or it must support the sequence
protocol (the __getitem__() method
with integer arguments starting at 0).

In [1]: 'foo'.__getitem__(0)
Out[1]: 'f'
Answered By: nmichaels

Probably because Python isn’t a langage that has a “char” type. The natural thing to return, if string did have __iter__ would be chars, but there are no chars. I can see a case for hooking __iter__ up to string and doing whatever list(someString) does, not really sure why it’s not that way.

Answered By: jpsimons
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.