SoFunction
Updated on 2024-11-17

Python yield Keywords.

1. Iterators

When you create a list, you can read its items one by one. Reading its items one by one is called iterating.

A mylist is an iterable object. When you use the list parser, you create a list, and therefore an iterator: the

All you can do with"for... in ...."It's all iterators, including lists, strings, files...and so on.

These iterators are very handy because you can read them as much as you want, but you're storing all the values in memory, which is a huge waste of memory when you have a lot of values.

In order to address suchPythonWith the concept of generators.

2. Generator

Generators are iterators, and such iterators can only iterate once. Generators don't store all values in memory, they generate them dynamically:.

It's similar to list parsing, except with () instead of []. However, you can't use themygeneratoris executed a second time for i, because the generator can only be used once: it prints(0) and then forgets about it, theprint(1) And finally, 4.

yieldIt's the one with thereturnSimilar keyword, except that the function will return a generator.

After carefully looking at the following example, we can fully understand.

function will return a set of values that only need to be read once. If you can make sense of this feature and apply it to your code, you may be able to improve performance dramatically, and next time we'll cover when to use it.

Note line 6 in the example, the code written in the body of the function does not run when the function is called. The function only returns the generator object, but do not forget the point.

Finally, your code will continue from where it stopped each time you used the generator. So the second time the generator is used in the example, our generator has no value at all.

So the core logic is as follows.

  • forThe first time a function calls the generator object created from the function, it will run the code in the function from scratch until it reaches theyieldthat returns the first value of the loop.
  • Subsequent calls will run the loop you wrote in the function again and YIELD returns the next value until there is no more value to return, as shown in our example above

Up to this point this article onPython yield Keywords, the article is introduced to this, more related Python yield keyword content please search my previous articles or continue to browse the following related articles I hope you will support me more in the future!