Python's Path to growth "fifth article": Python-based iterators and generators

Source: Internet
Author: User
I. Recursion and iteration

Recursion is calling itself

Iteration is that each iteration is dependent on the last result

Ii. What is an iterator protocol

1, iterator protocol refers to: the object must provide a next method, the execution of the method either returns the next item in the iteration, or causes a Stopiteration exception to terminate the iteration (can only go backward, not forward)

2. An iterative object: An object that implements an iterator protocol (how to: Define an __iter__ () method within an object)

3, the Protocol is a convention, can iterate over the object to implement the iterator protocol, Python's internal tools (such as for loops, Sum,min,max and other functions) are using the iterator protocol to access the object

Third, the powerful for loop mechanism in Python

The nature of the For loop: Loop through all objects, all using the iterator protocol

Radical reform

Many people will think that the nature of the For loop is to follow the iterator protocol to access the object, then the For loop object must be an iterator, yes, so that, for loop can traverse (string, list, tuple, dictionary, collection, file object) that these types of data must be an iterative object? But why do I define a list of a = [1, 2, 3, 4] without the A.next () method, punch the face?

(strings, lists, tuples, dictionaries, collections, file objects) These are not iterative objects, but in the for loop, they call their internal __iter__ method, turn them into an iterative object, and the For loop invokes the __next__ method of an iterative object to fetch the value, And the For loop catches the stopiteration exception to terminate the iteration

Python's Path to growth "fifth article": Python-based 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.