This article is participating in Python Theme Month. See the link for details
The iterator
Iteration is one of Python’s most powerful features, as a way of accessing elements of a collection.
An iterator is an object that remembers the position of the iterator.
Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only move forward and not backward.
Iterators have two basic methods: iter() and next().
String, list, or tuple objects can all be used to create iterators:
Instance-1: Next gets the elements of the iterator
>>>list= [1.2.3.4]
>>> it = iter(list)
Create an iterator object
>>> print (next(it))
1 Print the next element of the iterator
>>> print (next(it))
2
>>>
Copy the code
Instance-2: Iterator objects can be traversed using regular for statements
#! /usr/bin/python3
list= [1.2.3.4]
it = iter(list)
Create an iterator object
for x in it:
print(x, end="")
Copy the code
Execute the above program, the output result is as follows:
1 2 3 4
Copy the code
Example 3: You can also use the next() function
#! /usr/bin/python3
import sys
# introduce sys module
list= [1.2.3.4]
it = iter(list)
Create an iterator object
while True:
try:
print (next(it))
except StopIteration:
sys.exit()
Copy the code
Execute the above program, the output result is as follows:
1234
Copy the code
Create an iterator
-
Using a class as an iterator requires implementing two methods in the class: __iter__() and __next__().
-
If you’re familiar with object-oriented programming, you know that classes have a constructor. Python’s constructor is __init__(), which is executed when the object is initialized.
-
The iter() method returns a special iterator object that implements the __next__() method and marks the completion of the iteration with a StopIteration exception.
-
The next() method (next() in Python 2) returns the next iterator object.
-
Create an iterator that returns a number, starting at 1 and incrementing by 1:
Example: Create iterators
class MyNumbers:
def __iter__(self) :
self.a = 1
return self
def __next__(self) :
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
Copy the code
The output is as follows:
12345
Copy the code
StopIteration
The StopIteration exception is used to indicate the completion of an iteration and to prevent infinite loops. In the __next__() method we can set the StopIteration exception to be raised to terminate the iteration after the specified number of loops have been completed.
Stop execution after 20 iterations:
Example: StopIteration
class MyNumbers:
def __iter__(self) :
self.a = 1
return self
def __next__(self) :
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raiseStopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
Copy the code
The output is as follows:
1234567891011121314151617181920
Copy the code
The generator
In Python, functions that use yield 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 easier to understand that a generator is an iterator.
During a call generator run, each time yield is encountered, the function pauses and saves all current run information, returns the yield value, and continues from the current position on the next execution of the next() method.
Call a generator function that returns an iterator object.
The following example implements the Fibonacci sequence using yield:
Example: Generator
#! /usr/bin/python3
import sys
def fibonacci(n) :
# Generator function - Fibonacci
a, b, counter = 0.1.0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f is an iterator generated by a generator return
while True:
try:
print (next(f), end="")
except StopIteration:
sys.exit()
Copy the code
Execute the above program, the output result is as follows:
0 1 1 2 3 5 8 13 21 34 55
Copy the code