Day④: iterators

Source: Internet
Author: User



Iterators are a way to access the elements of a collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without going backwards, but that's fine, because people seldom retreat in the middle of an iteration. In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it ideal for traversing large or infinite collections, such as several G files


    1. The visitor does not need to care about the structure inside the iterator, but simply continues to fetch the next content through the next () method
    2. A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end
    3. You can't go back halfway through the interview.
    4. Facilitates recycling of large data sets, saving memory
  1. #!/usr/bin/python
  2. #coding=utf-8
  3. names=iter([‘yaobin‘,‘hy‘,‘test‘])
  4. print(names)
  5. print(names.__next__())
  6. print(names.__next__())
  7. print(names.__next__())
  8. print(names.__next__())
  9. 结果:
  10. <list_iterator object at 0x00000000010ED160>
  11. yaobin
  12. hy
  13. test
  14. Traceback (most recent call last):
  15. File "D:/Users/bin/PycharmProjects/s12/day4/迭代器", line 11, in <module>
  16. print(names.__next__())
  17. StopIteration

#迭代器只有__next__方法, there's nothing else.


From for notes (Wiz)

Day④: iterators

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.