Python iterators and generators

Source: Internet
Author: User

 for inch [1, 2, 3]: Print (Element)

Can for...in ... As an iterative object

An iterator is an object that remembers where to traverse. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.

Judging method:

Isinstance ()

Iterator Definition Method:

classReverse:"""Iterator for looping over a sequence backwards."""    def __init__(self, data): Self.data=Data Self.index=len (data)def __iter__(self):return Selfdef __next__(self):ifSelf.index = =0:Raisestopiteration Self.index= Self.index-1returnSelf.data[self.index]

Generator:

 

DEF reverse (data):    for index in range (LEN (data)-1,-1,-1):        yield Data[index]

The builder is a simple and efficient tool for creating iterators:

1. Automatically create __ITER__ () and __next__ ()

2. Automatically save local variables and execution status

Yield can be simply understood as returning the return of an iterator

List parsing and builder expressions:

(X+1 for x in LST) #生成器表达式, returns an iterator. External parentheses can be omitted when used with parameters.

[X+1 for x in LST] #列表解析, return to list

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.