Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement iterator and generator in Python

Shulou Source: shulou.com Published: 2022-06-02 06:50:19 10月21日 Update

This article will explain in detail how to implement iterators and generators in Python. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Iterator of function

The powerful function is called an iterator, one of the most powerful functions in Python. Iterator sounds very strange to us. It is useful in both list and tuple. We use for and in to take each element in the list and deal with each element in turn. This method is called iteration, and the function that implements this method is called iterator. There are two basic functions in the iterator, this function is called method, which is called a method in object-oriented programming, and these two methods are called iter () and next ().

1. What is iteration? Iteration is a repetitive process, and each iteration is based on the previous result.

two。 If you want to know what an iterator is? You must first understand the concept of what is an iterable object? Iterable objects: in python, all objects with built-in 'iter'' methods are iterable objects.

3. Iterator: iterative value tool. The iterator object is returned when the iterated object executes the iter method.

An example demonstration-an iterator defines a list that is processed into processor list1= [1 next (it)) print (next (it))

Example demonstration-output exception list1= [1je 2je 3je 4] it=iter (list1) # assignment variable print (next (it)) # except, error message StopIteration will be reported if it exceeds the list range

Summary

Each call to next () outputs the next element in iter ()

Until the output is complete.

An exception occurs when the length is exceeded.

Generator of function

We feel the power of the iterator, how to make an iterator ourselves?

Example demonstration-simple iterator range () function

For i in range: # the first parameter is the start parameter, the second parameter is the end parameter, and the third parameter is the step print (I)

If the step size is decimal 0.5 or not, the wrong type information will be returned.

The Range () function must be an integer

Example demonstration-how to optimize the above problems and support decimals

Referring to yield, a function with yield is called a generator

Def frange (start,stop,step): x=start# defines a variable while x

Tags: Iterations functions objects methods parameters generators generation presentation location elements functions variables processing output powerful two information content decimals articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB vpn Microsoft NVidia Linux