DEV Community

Cover image for Generators and yield in python 🤓
Phoenix
Phoenix

Posted on

Generators and yield in python 🤓

Generators

Generators are functions that can be stopped while running and then resumed. These functions return an object that can be scrolled. Unlike lists, generators are lazy, which causes the calculation and evaluation of a phrase to be delayed as much as possible and to be calculated as soon as it was needed. These functions make memory usage more efficient when working with large data sets.

Differences between generators and normal Python functions:

  • To call the next values ​​in the generator, we use the next () method.

  • In normal functions we use return to return values, but in generator we use yield (the yield statement acts to stop the function and save its status to continue working in the future from where it left off).

  • Generators are also iterators, meaning that the classes we define have the __ (iter__) method defined in them.

Example of generator

In the following code we have a generator function that takes the list as an argument and returns the sum of the numbers of its elements:

def myGenerator(l):  
     total = 0
     for n in l:
       total += n
       yield total
mygenerator = myGenerator([15,10, 7])
print(mygenerator)
print(next(mygenerator))
print(next(mygenerator))
print(next(mygenerator))
Enter fullscreen mode Exit fullscreen mode

Output:

<generator object myGenerator at 0x0000026B84B6C150>
15
25
32

We see that a new value is displayed for each call of the next method. If you re-read the function, you will get an error saying "You can not navigate".

Traceback (most recent call last):
File "generators.py", line 13, in <module>
print(next(mygenerator))
StopIteration

Do not forget to like!
Bye until the next post👋😘

Top comments (1)

Collapse
 
epsi profile image
E.R. Nurwijayadi

Good article. Thank you for posting.

I have written simple code as a yield-next example. This might be useful as a complementary resource for your reader. The source code is available in github.

🕷 epsi.bitbucket.io/lambda/2021/01/0...

First the data structure:

Songs Record

Then sender and receiver.

Sender

Receiver

And run both functions.

Main

I hope this could help other who seeks for other case example.

🙏🏽

Thank you for posting about general introduction of generator in python.