Python iterators and generators

Source: Internet
Author: User

1. iterators

Iterators are a way to access the elements of a collection. An iterator object is accessed from the first element of the collection, knowing that 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.

1.1 Advantages of using iterators

For primitive data structures that support random access (such as tuple, list), there is no advantage over the index access of the iterator and the classic for loop, but the index value is lost (you can use the built-in function enumerate () to retrieve the index value). But for data structures that cannot be accessed randomly (such as set), iterators are the only way to access elements.

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 particularly useful for traversing large or infinite collections, such as several G files, or Fibonacci sequences, and so on.

The greater credit for iterators is the provision of an interface for a unified access collection, which can be accessed using iterators as long as the __iter__ () method object is defined.

There are two basic methods for iterators

  • Next method: Returns the next element of the iterator
  • __iter__ method: Returns the Iterator object itself

The following is an example of how to generate Fibonacci numbers to illustrate why iterators

Python iterators and generators

Related Article

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: info-contact@alibabacloud.com 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.