Iterate objects and iterator objects in Python

Source: Internet
Author: User

Just learning Python, the individual understanding of "iterative objects" and "iterator objects" doesn't know right.

1. Several concepts

1. Iterative tools: Includes for loop, list resolution, in membership test ..... And so on, to access the actions (?) of the elements in an iterative object (container) in turn.

2. Iterator object: An object with the __next__ () method. The method can automatically return the next result, and when the end of the sequence is reached, the stopiteration exception is thrown.

3. Iterative object: An object with the __iter__ () method. The method can get its iterator object.

2. Iterative process (for example for loop)

For loop start: Automatically invokes the __iter__ () method of an iterative object to get its iterator object (containing the next method)

For loop: Automatically invokes the __next__ () method of an Iterator object to get the next element

For Loop end: When the __next__ () call throws a Stopiteration exception, the loop ends.

3. A few notes

(1) An Iterator object can also be an iterator object, such as a file object. At this point, you can iterate over the object itself with the __next__ () method, and its __iter__ () method returns its own

(2) For many built-in objects and their derived objects, such as list, dict, etc., because they need to support opening iterators multiple times, so they are not iterator objects, they need to return their iterator objects with the __iter__ () method and use the iterator object to access the other elements.

Iterate objects and iterator objects in Python

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.