I was checking out str objects in Python, and I realized that str object in Python 2.7 doesn't have either __iter__()
method nor next()
method, while in Python 3.0 str objects have __iter__()
method, and thus they are iterable. However, I can still use str objects as if they are iterable's in Python 2.7. For example, I can use them in for loops. How does this work?
Simple answer: because iter(s)
returns an iterable object.
Longer answer: iter()
looks for an __iter__()
method, but if it doesn't find one it tries to construct and iterator itself. Any object that supports __getitem__()
with integer indices starting at 0 can be used to create a simple iterator. __getitem__()
is the function behind list/string indexing operations, eg s[0]
.
>>> "abc".__iter__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__iter__'
>>> iter("abc")
<iterator object at 0x1004ad790>
>>> iter("abc").next()
'a'
See here for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With