Graphic python iterator and generator

Posted by gordong1968 on Wed, 23 Feb 2022 07:50:19 +0100

Author: Han Xinzi@ShowMeAI

Tutorial address: http://www.showmeai.tech/tutorials/56

Article address: http://www.showmeai.tech/article-detail/82

Notice: All Rights Reserved. Please contact the platform and the author for reprint and indicate the source

1.Python iterator

Iteration is one of Python's most powerful features and a way to access collection elements.

An iterator is an object that remembers where to traverse.

The iterator object is accessed from the first element of the collection until all the elements are accessed. Iterators can only move forward, not backward.

Iterators have two basic methods: iter() and next().

String, list, or tuple objects can be used to create iterators:

list=[1,2,3,4]
it = iter(list)    # Create iterator object
print(next(it))   # Next element of output iterator 1
print(next(it))   # Next element of output iterator 2

Iterator objects can be traversed using regular for statements( Online Python 3 environment):

l=['Baidu', 'ShowMeAI', 'google', 'ByteDance']
it = iter(l)    # Create iterator object
for x in it:
  print(x)

Execute the above procedures, and the output results are as follows:

Baidu
ShowMeAI
google
ByteDance

You can also use the next() function( Online Python 3 environment):

list=['Baidu', 'ShowMeAI', 'google', 'ByteDance']
it = iter(list)    # Create iterator object
 
while True:
    try:
        print(next(it))
    except StopIteration:
        break

Execute the above procedures, and the output results are as follows:

Baidu
ShowMeAI
google
ByteDance

(1) Create an iterator

To use a class as an iterator, you need to implement two methods iter() and next() in the class.

If you already know about object-oriented programming, you know that classes have a constructor. Python's constructor is init(), which will be executed when the object is initialized.

For more information: Python object oriented

The iter() method returns a special iterator object that implements the next() method and identifies the completion of the iteration through the StopIteration exception.

The next() method (next() in Python 2) returns the next iterator object.

Create an iterator that returns a number, with an initial value of 1 and incremented by 1( Online Python 3 environment):

class IterNumbers:
  def __iter__(self):
    self.a = 1
    return self
 
  def __next__(self):
    x = self.a
    self.a += 1
    return x
 
num_class = IterNumbers()
iter_num = iter(num_class)
 
print(next(iter_num))
print(next(iter_num))
print(next(iter_num))
print(next(iter_num))
print(next(iter_num))

The execution output is:

1
2
3
4
5

(2)StopIteration

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.

Stop execution after 10 iterations( Online Python 3 environment):

class IterNumbers:
  def __iter__(self):
    self.a = 1
    return self
 
  def __next__(self):
    if self.a <= 10:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration
 
num_class = IterNumbers()
iter_num = iter(num_class)
 
for x in iter_num:
  print(x)

The execution output is:

1
2
3
4
5
6
7
8
9
10

2. Generator

In Python, functions that use yield are called generator s.

Unlike ordinary functions, a generator is a function that returns an iterator and can only be used for iterative operations.

In the process of calling the generator to run, the function will pause and save all the current running information every time it encounters yield, return the value of yield, and continue to run from the current position the next time it executes the next() method.

Call a generator function and return an iterator object.

The following example uses yield to implement Fibonacci sequence( Online Python 3 environment):

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 that is returned by the generator
 
while True:
    try:
        print(next(f))
    except StopIteration:
        break

Execute the above procedures, and the output results are as follows:

0
1
1
2
3
5
8
13
21
34
55

3. Video tutorial

Please click to station B to view the version of [bilingual subtitles]

https://www.bilibili.com/video/BV1yg411c7Nw

Data and code download

The code for this tutorial series can be found in github corresponding to ShowMeAI Download in, you can run in the local python environment. Babies who can surf the Internet scientifically can also directly use Google lab to run and learn through interactive operation!

The Python quick look-up table involved in this tutorial series can be downloaded and obtained at the following address:

Extended references

ShowMeAI related articles recommended

ShowMeAI series tutorial recommendations