Python3 iterators and generators

Source: Internet
Author: User

Iterators

Iteration is one of the most powerful features of Python and is a way to access the elements of a collection.

An iterator is an object that you can remember to traverse a position.

The iterator is accessed from the first element of the collection until all the elements have been accessed and finished. Iterators can only move forward without backing back.

There are two basic methods of iterators: ITER () and Next ()

A string, list, or tuple object can be used to create iterators.

Iterator objects can be traversed using a regular for statement

You can also use the next () function

Generator

In Python, a function that uses yield is called a generator (generator).

Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.

In the process of calling the generator to run, the function pauses and saves all current run information, returns the value of yield, and continues running from its current location the next time the next () method is executed, each time yield is encountered.

Invokes a generator function that returns an Iterator object.

Compared with yield and not the case

Yield execution Results

No yield execution results

Under what circumstances will yield be used?

A function f,f returns a list, which is dynamically computed (either mathematically or logically, and the list is large (either fixed or enlarged with the increase in input parameters), and this is the time at which the It is useful to have a single list element instead of a complete list to save memory each time we call this function and use an iterator to loop it.

Python3 iterators and generators

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.