Python basic notes - iterators and generators

Posted by ma5ect on Fri, 18 Feb 2022 20:06:51 +0100


  1. Iteration is one of the most powerful functions of python and a way to access collection elements
  2. An iteration is an object that can remember the traversal position
  3. The object of the iterator is accessed from the first object of the collection until the access is over, and the iterator only moves forward
  4. The basic methods of iterators: iter() and next()

The essence of an iteratable object is that it can provide us with such an intermediate "person", that is, an iterator, to help us iterate over it.
Iteratable object passing__ iter__ Method provides us with an iterator. When we iterate over an iteratable object, we actually get an iterator provided by the object first
After that, each data in the object is obtained in turn through this iterator.

list = [1, 2, 3, 4, 5]		# Create list
l = iter(list)	# Create iterator
print(next(l))	# Output element (first) 	 one
print(next(l))	# Output element (second) 	 two
print(next(l))	# Output element (third) 	 three
The iterator can also use the for loop to iterate and output all elements
list = [1, 2, 3, 4, 5]	# Create list
l = iter(list)	# Create iterator
for i in l:		# Loop traversal
    print(i, end=' ')	# Output the data after the cycle, end station space
# Results: 1 2 3 4 5

# next function
list = [1, 2, 3, 4, 5]	# Definition list
l = iter(list)	# Create iterator
while True:		# Infinite loop
    try:		# judge
        print(next(l))	# output
    except StopIteration:	# Prevent error StopIteration
# Results: 1 2 3 4 5

Create iterator

  • To create an iterator, you need to use it in your class__ iter__ () and__ nect__ () method. Note: two_
  • init() method: returns a special iterator object, which is called__ next()__ Method, and it is completed through the stop exception prompt
  • next() method: returns the next iterator object
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)
# Results: 1 2 3 4


The StopIteration exception is used to identify the completion of the iteration and prevent infinite loops. In the next() method, we can set the StopIteration exception to be triggered after completing the specified number of cycles to end the iteration.
class MyNumbers:	# Define function
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a <= 6:	# Define the number of cycles
            x = self.a
            self.a += 1
            return x
            raise StopIteration	# Report and return
myclass = MyNumbers()	# Transfer function value
myiter = iter(myclass) # Define iterators
for x in myiter:	# Loop through and output
# Results: 1 2 3 4 5 6


  • python uses the yield method to define the generator, which can only be used for iterative operation, that is, to generate an iterator
  • When running the generator, the yield function will pause and save the current information, and continue to run from the current position the next time the next() method is executed.
# Generate Fibonacci sequence
import sys	# Import sys
def fibonacci(n):  # Generator function - Fibonacci
    a, b, counter = 0, 1, 0	# Definition number
    while True:			# Infinite loop
        if (counter > n):	# Circular judgment
            return			# Return null
        yield a		# generator 
        a, b = b, a + b	# definition
        counter += 1	# Self increasing
f = fibonacci(10)  # f is an iterator that is returned by the generator
while True:# Infinite loop
    try:	# No error message
        print(next(f), end=" ")	# Output results
    except StopIteration:	# r to report StopIteration error

Fibonacci sequence, also known as golden section sequence and rabbit sequence, was proposed by mathematician Leonardo Fibonacci in 1202. Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13, 21, 34... This sequence starts from item 3, and each item is equal to the sum of the first two items. The recurrence formula is F(n)=F(n-1)+F(n-2), n ≥ 3, F(1)=1, F(2)=1

Topics: Python