Table of Contents
1. What is a generator
2. Create a generator method
Method 2
3.send
4. Implement multi-tasking
3. Iterator
1. Iterable objects
2. Determine whether iterable
4.iter() function
6. Closure
2. What is closure
3. Look at a practical example of closure:
Home Backend Development Python Tutorial Python-detailed explanation of generators

Python-detailed explanation of generators

Jun 23, 2017 pm 03:10 PM

1. What is a generator

With list generation, we can directly create a list. However, due to memory constraints, the list capacity is definitely limited. Moreover, creating a list containing 1 million elements not only takes up a lot of storage space, but if we only need to access the first few elements, the space occupied by most of the subsequent elements will be wasted. So, if the elements of the list can be calculated according to a certain algorithm, can we continuously calculate the subsequent elements during the loop? This eliminates the need to create a complete list, saving a lot of space. In Python, this mechanism of looping and calculating at the same time is called a generator: generator.

2. Create a generator method

Method 1

There are many ways to create a generator. The first method is very simple, just change the [ ] of a list generation to ( )

The difference between creating L and G is only the outermost [ ] and ( ), L is a list, and G is a generator. We can directly print out each element of L, but how do we print out each element of G? If you want to print them out one by one, you can get the next return value of the generator through the next() function:


Running results:

Running results:

The generator saves the algorithm, and each time next( is called G), calculate the value of the next element of G until the last element is calculated. When there are no more elements, a StopIteration exception is thrown. Of course, this kind of continuous calling next() is really abnormal. The correct method is to use a for loop, because the generator is also an iterable object. So, after we create a generator, we basically never call next(), but iterate it through a for loop, and don't need to care about the StopIteration exception.

Method 2

generator is very powerful. If the calculation algorithm is relatively complex and cannot be implemented using a for loop similar to list generation, it can also be implemented using a function.

For example, in the famous Fibonacci sequence, except for the first and second numbers, any number can be obtained by adding the first two numbers:

1 , 1, 2, 3, 5, 8, 13, 21, 34, ...

The Fibonacci sequence cannot be written using list generation, but it is easy to print it out using a function :


Run result:

Looking carefully, you can see that the fib function is actually defined After understanding the calculation rules of the Fibonacci sequence, you can start from the first element and calculate any subsequent elements. This logic is actually very similar to the generator.

In other words, the above function is only one step away from the generator. To turn the fib function into a generator, just change print(b) to yield b:


Running results:

In the above example of fib, if we keep calling yield during the loop, it will continue to be interrupted. Of course, you need to set a condition for the loop to exit the loop, otherwise an infinite number will be listed. Similarly, after changing the function to generator, we basically never use next() to get the next return value, but directly use the for loop to iterate:

Running results:

#But when calling the generator using a for loop, I found that I could not get the return value of the generator's return statement. If you want to get the return value, you must capture the StopIteration error. The return value is included in the value of StopIteration:


Running result:

3.send

Example: When yield is executed, the gen function is temporarily saved and returns the value of i; temp receives the value sent by c.send("python") next time, c .next() is equivalent to c.send(None)

Use next function


Running result:

Use __next__() method


Running result:

Use send

Run result:

4. Implement multi-tasking

Simulate multi-tasking implementation method One: Coroutine


Run result:

Summary

Generator is a function that remembers the position in the function body when it last returned. The second (or nth) call to a generator function jumps to the middle of the function, leaving all local variables unchanged from the previous call.

A generator not only "remembers" the state of its data; a generator also "remembers" its position within a flow control construct (in imperative programming, this construct is not just a data value).

Features of the generator:

1. Save memory

2. When iterating to the next call, the parameters used are all retained from the first time. , that is to say, the parameters of all function calls are retained when called for the first time, rather than newly created

5. Iterator

Iteration is to access the elements of the collection a method. An iterator is an object that remembers the position of a traversal. The iterator object starts accessing from the first element of the collection until all elements have been accessed. Iterators can only go forward and not backward.

1. Iterable objects

The data types that directly act on the for loop are as follows:

The first type is collection data types, such as list, tuple, dict , set, str, etc.;

One category is generator, including generator and generator function with yield.

These objects that can be directly used in for loops are collectively called iterable objects: Iterable.

2. Determine whether iterable

You can use isinstance() to determine whether an object is an Iterable object:


Running results:

The generator can not only act on the for loop, but can also be continuously called by the next() function and return the next value, until finally a StopIteration error is thrown to indicate that it cannot Continue to return to the next value.

3. Iterator

An object that can be called by the next() function and continuously returns the next value is called an iterator: Iterator.


Running result:

4.iter() function

Generator They are all Iterator objects, but although list, dict, and str are Iterable, they are not Iterators.

To convert list, dict, str and other Iterables into Iterator, you can use the iter() function:


Running result:

Summary

·All objects that can be used in the for loop are of type Iterable;

·All objects that can be used in the next() function are of type Iterator

·Collection data types such as list, dict, str, etc. are Iterable but not Iterator, but you can obtain an Iterator object through the iter() function.

·The purpose is to reduce the occupied content when using collections.

6. Closure

1. Function reference


Running result:

Illustration:

2. What is closure


Run result:

3. Look at a practical example of closure:


Run result:

In this example, the function line and variables a and b form a closure. When creating the closure, we specify the values ​​of these two variables through the parameters a and b of line_conf. In this way, we determine the final form of the function (y = x + 1 and y = 4x + 5). We only need to transform the parameters a and b to obtain different straight line expression functions. From this, we can see that closures also have the effect of improving code reusability.

If there is no closure, we need to specify a, b, x every time we create a straight line function. In this way, we need to pass more parameters, which also reduces the portability of the code. If you encounter any problems during the learning process or want to obtain learning resources, you are welcome to join the learning exchange group

626062078, we Learn Python together!

The above is the detailed content of Python-detailed explanation of generators. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles