python iterables and iterators

Often mistakes are made when building iterables and iterators, because the two are mixed up. You must know that iterable objects have a __iter__ method, which instantiates a new iterator each time; and the iterator must implement the __next__ method, which returns a single element, and the __iter__ method, which returns the iterator itself.

Therefore, iterators can iterate, but iterable objects are not iterators.

For example, the string "hello world" is an iterable object. Calling the iter method on the string (it = iter("hello world")) will return an iterator it, which has the __iter__ method and the __next__ method. The __next__ method puts back the next element, and the __iter__ method returns the iterator itself.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325222935&siteId=291194637