Python 3 iterator and generator, Python3 Generator
Iterator
Iteration is one of the most powerful functions of Python and a way to access collection elements ..
An iterator object is an object that can remember the traversal position.
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.
The iterator has two basic methods:Iter ()AndNext ().
String, list, or tuples can be used to create an iterator.
Example:
List = [1, 2, 3, 4]
It = iter (list) # create iterator object
Print (next (it) # next element of the output iterator
For I in it: # for Loop Traversal
Print (I, end = "")
Result: 1
2 3 4
You can also:
Import sys
List = [1, 2, 3, 4]
It = iter (list)
While True:
Try:
Print (next (it ))
Optional t StopIteration:
Sys. exit ()
Result:
1
2
3
4
Generator
In Python, yield functions are called generators ).
Unlike normal functions, a generator is a function that returns an iterator and can only be used for iterative operations.
It is simpler to understand that the generator is an iterator.
When the generator is called to run, the function will pause and save all running information each time yield is encountered, and the yield value will be returned.
The next execution of the next () method continues from the current position.
The following example uses yield to implement the Fibonacci sequence:
Import sys
Def fibonaqie (n): # generator function-Fibonacci Series
A, B, counter = 0, 1, 0
While True:
If (counter> n ):
Return
Yield
A, B = B, a + B
Counter + = 1
Fi = fibonaqie (10) # fi is an iterator returned by the generator.
While True:
Try:
Print (next (fi), end = "")
Optional t StopIteration:
Sys. exit ()
Results: 0 1 1 2 3 5 8 13 21 34 55