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?
I was checking out str objects in Python, and I realized that str object
Share
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, egs[0].See here for details.