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