Python development [Article 1] Generator and iterator of Python basics, Article 1 python

Source: Internet
Author: User

Python development [Article 1] Generator and iterator of Python basics, Article 1 python
Generator and iterator

1. Generator

When a function is called, an iterator is returned. This function is called a generator. If the function contains the yield syntax, this function will become a generator;

def func():    yield 1    yield 2    yield 3ret = func()for i in ret:    print(i)

Go to the function to find yield and return the data after yield.

def myrange(arg):    start = 0    while True:        if start > arg:            return        yield start        start += 1ret = myrange(3)r = ret.__next__()print(r)r = ret.__next__()print(r)r = ret.__next__()print(r)r = ret.__next__()print(r)

 

2. iterator

Code rendering (Compilation) is executed from bottom up, and code execution is performed from top down.

An iterator is a way to access collection elements. The iterator object is accessed from the first element of the set until all elements are accessed. The iterator can only move forward without moving back, but there is nothing to do with it, because people seldom go back on the way of iteration. In addition, the major advantage of the iterator is that it is not required to prepare all elements in the entire iteration process in advance. The iterator calculates an element only when it iterates to an element. Before or after this, the element may not exist or be destroyed. This feature makes it especially suitable for Traversing large or infinite sets, such as several G files.

Features:

Inside the iterator is _ next __, and inside the for loop is encapsulated as _ next __.

 

Illustration:

 

3. Instance

A. Use the generator to customize the range

def nrange(num):    temp = -1    while True:        temp = temp + 1        if temp >= num:            return        else:            yield temp

B. Use the iterator to access range

...

  

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.