Basic usage analysis of Python iterator and generator

  • 2020-11-18 06:22:13
  • OfStack

This article illustrates the basic use of Python iterators and generators. To share for your reference, the details are as follows:

The iterator

There are two types of data that can be used for for loops:

1. Collection data types such as list . tuple . dict . str Etc.

2. The other is a generator

And they're all iterable objects, called Iterable

Isinstandce() Can be used to determine whether an object is iterable or not


>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance({}, Iterable)
True
>>> isinstance('abc', Iterable)
True
>>> isinstance((x for x in range(10)), Iterable)
True
>>> isinstance(100, Iterable)
False

Then, only generators can be called iterators because they are constantly used next() The function returns a value, which is a lazy calculation, and there is also a judgment function for iterators


>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('abc', Iterator)
False

The generator

Generator: the list that is not finished loop, this is to save computer memory, set up a 1 side loop 1 side calculation mechanism.

The method of creation is also very simple, one of which is to generate the list [] to () It is ok

Instead of the troublesome next() method, the call is traversed by the for loop

Such as:


g= (x*x for x in range(10))
for n in g:
 print(n)

This allows you to iterate over all the elements in the generator

Another generator approach: This is a generator if the function contains the yield keyword


def odd():
  print('step 1')
  yield 1
  print('step 2')
  yield(3)
  print('step 3')
  yield(5)

For more readers interested in Python, please refer to Python Data Structure and Algorithm Tutorial, Python Encryption and Decryption Algorithm and Techniques Summary, Python Coding skills Summary, Python Function Usage Tips summary, Python String Manipulation Skills Summary and Python Introductory and Advanced Classic Tutorial.

I hope this article is helpful for Python programming.


Related articles: