avatarAayushi Johari

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

6983

Abstract

</figcaption></figure><p id="97cb">The above image shows the execution of our program required a number of times. If you try to call the next function again, it returns a message depicting <b><i>StopIteration</i></b> has been implemented. If you try to do this with normal functions, the values returned will not change or iterate. Take a look at the example below:</p><p id="9680"><b>EXAMPLE:</b></p><div id="ec5b"><pre>def z()<span class="hljs-symbol">:</span> <span class="hljs-built_in">n</span>=<span class="hljs-number">1</span> <span class="hljs-built_in">yield</span> <span class="hljs-built_in">n</span> <span class="hljs-built_in">n</span>=<span class="hljs-built_in">n</span>+<span class="hljs-number">3</span> <span class="hljs-built_in">yield</span> <span class="hljs-built_in">n</span> p=z() next(p)</pre></div><p id="9e34"><b>OUTPUT:</b></p><figure id="2102"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*DyrD_Y19wThG0Ro28m9tFg.png"><figcaption></figcaption></figure><h1 id="52d6">Generators with loops:</h1><p id="7f9b">In case you want to execute the same function at once, you can make use of the ‘for’ loop. This loop helps iterate over the objects and after all implementations it executes StopIteration.</p><p id="7f6a"><b>EXAMPLE:</b></p><div id="4748"><pre>def z()<span class="hljs-symbol">:</span> <span class="hljs-built_in">n</span>=<span class="hljs-number">1</span> <span class="hljs-built_in">yield</span> <span class="hljs-built_in">n</span> <span class="hljs-built_in">n</span>=<span class="hljs-built_in">n</span>+<span class="hljs-number">3</span> <span class="hljs-built_in">yield</span> <span class="hljs-built_in">n</span> for x in z()<span class="hljs-symbol">:</span> print(x)</pre></div><p id="b179"><b>OUTPUT:</b></p><p id="a246">1 4</p><p id="3fad">You can also specify expressions to generate iterable objects.</p><h2 id="c840">Generator Expressions:</h2><p id="71a7">You can also use expressions along with the for loop to produce iterators. This usually makes the generation iterables much easy. Generator expression resemble list comprehensions and like lambda functions, generator expressions create anonymous generator functions.</p><p id="9012">Take a look at the example below:</p><p id="540d"><b>EXAMPLE:</b></p><div id="2465"><pre><span class="hljs-attribute">a</span>=range(6) <span class="hljs-built_in">print</span>(<span class="hljs-string">"List Comprehension"</span>, <span class="hljs-attribute">end</span>=<span class="hljs-string">':'</span>) b=[x+2 <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> a] <span class="hljs-built_in">print</span>(b) <span class="hljs-built_in">print</span>(<span class="hljs-string">"Generator expression"</span>, <span class="hljs-attribute">end</span>=<span class="hljs-string">':n'</span>) c=(x+2 <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> a) <span class="hljs-built_in">print</span>(c) <span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> c: <span class="hljs-built_in">print</span>(y)</pre></div><p id="d16c"><b>OUTPUT:</b></p><p id="013a">List Comprehension:[2, 3, 4, 5, 6, 7]</p><p id="773b">Generator expression:</p><p id="904b"><generator object="" <genexpr=""> at 0x0000016362944480&gt;</generator></p><p id="d7e7">2 3 4 5 6</p><p id="6821">As you can see, in the above output, the first expression is a list comprehension which is specified within [] brackets. List comprehension produces the complete list of items at once. The next is a generator expression that returns the same items but one at a time. It is specified using () brackets.</p><p id="c618">Generator functions can be used within other functions as well. For example:</p><p id="70b9"><b>EXAMPLE:</b></p><div id="7295"><pre><span class="hljs-attribute">a</span>=range(6) <span class="hljs-built_in">print</span>(<span class="hljs-string">"Generator expression"</span>, <span class="hljs-attribute">end</span>=<span class="hljs-string">':n'</span>) c=(x+2 <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> a) <span class="hljs-built_in">print</span>(c) <span class="hljs-built_in">print</span>(min(c))</pre></div><p id="a899"><b>OUTPUT:</b></p><p id="651b">Generator expression 2</p><p id="ed89">The above program prints the min value when the above expression as applied to the values of a.</p><h1 id="a8d1">Use Cases:</h1><p id="eff5">Let us use Generators in Python to:</p><ul><li>Generate Fibonacci Series</li><li>Generating Numbers</li></ul><h2 id="9b49">Generating Fibonacci Series:</h2><p id="49fa">Fibonacci series as we all know is a series of numbers wherein each number is a sum of preceding two numbers. The first two numbers are 0 and 1. Here is a generator program to generate Fibonacci series:</p><p id="2ddc"><b>EXAMPLE:</b></p><div id="e014"><pre>def fibo(): <span class="hljs-built_in">first</span>,<span class="hljs-built_in">second</span>=<span class="hljs-number">0</span>,<span class="hljs-number">1</span> <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>: yield <span class="hljs-built_in">first</span> <span class="hljs-built_in">first</span>,<span class="hljs-built_in">second</span>=<span class="hljs-built_in">second</span>,<span class="hljs-built_in">first</span>+<span class="hljs-built_in">second</span> <span class="hljs-keyword">for</span> x in fibo(): <span class="hljs-keyword">if</span> x&gt;<span class="hljs-number">50</span>: <span class="hljs-keyword">break</span> print(x, end=<span class="hljs-string">" "</span>)</pre></div><p id="5ebc"><b>OUTPUT:</b></p><div id="1b29"><pre><span class="hljs-symbol">0 </span><span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span> <span class="hljs-number">5</span> <span class="hljs-number">8</span> <span class="hljs-number">13</span> <span class="hljs-number">21</span> <span class="hljs-number">34</span></pre></div><p id="1c94">The above output shows the Fibonacci series with values less than 50. Let’s now take a look at how to generate a list of numbers.</p><h1 id="cbbc">Generating Numbers:</h1><p id="b4bd">In case you want to generate specified list numbers, you can do it using generator functions. Take a look a look at the following example:</p><p id="233a"><b>EXAMPLE:</b></p><div id="5659"><pre><span class="hljs-variable">a</span>=<span class="hljs-function"><span class="hljs-title">range</span>(<span class="hljs-number">10</span>)</span> <span class="hljs-variable">b</span>=(<span class="hljs-variable">x</span> <span class="hljs-variable">for</span> <span class="hljs-variable">x</span> <span class="hljs-variable"><span class="hljs-keyword">in</span></span> <span class="hljs-variable">a</span>) <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variabl # Options e">b</span>)</span> <span class="hljs-variable">for</span> <span class="hljs-variable">y</span> <span class="hljs-variable"><span class="hljs-keyword">in</span></span> <span class="hljs-variable">b</span>: <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable">y</span>)</span></pre></div><p id="80a7"><b>OUTPUT:</b></p><p id="e108"><generator object="" <genexpr=""> at 0x000001CBE1602DE0&gt;</generator></p><p id="2b65">0 1 2 3 4 5 6 7 8 9</p><p id="149f"><b>EXAMPLE:</b></p><div id="b907"><pre><span class="hljs-attribute">a</span>=range(2,10,2) b=(x <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> a) <span class="hljs-built_in">print</span>(b) <span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> b: <span class="hljs-built_in">print</span>(y)</pre></div><p id="9d2a"><b>OUTPUT:</b></p><p id="2f24"><generator object="" <genexpr=""> at 0x000001CBE1623138&gt; 2 4 6 8</generator></p><p id="7711">The above program has returned even numbers from 2 to 10. This brings us to the end of this article on Generators in Python. I hope you have understood all the topics.</p><p id="2dec"><b><i>Make sure you practice as much as possible and revert your experience.</i></b></p><p id="f224">If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=generators-in-python">Edureka’s official site.</a></p><p id="f20e">Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.</p><blockquote id="1dbe"><p>1. <a href="https://readmedium.com/machine-learning-classifier-c02fbd8400c9">Machine Learning Classifier in Python</a></p></blockquote><blockquote id="cf6f"><p>2. <a href="https://readmedium.com/python-scikit-learn-cheat-sheet-9786382be9f5">Python Scikit-Learn Cheat Sheet</a></p></blockquote><blockquote id="4e79"><p>3. <a href="https://readmedium.com/python-libraries-for-data-science-and-machine-learning-1c502744f277">Machine Learning Tools</a></p></blockquote><blockquote id="1833"><p>4. <a href="https://readmedium.com/python-libraries-for-data-science-and-machine-learning-1c502744f277">Python Libraries For Data Science And Machine Learning</a></p></blockquote><blockquote id="4da3"><p>5. <a href="https://readmedium.com/how-to-make-a-chatbot-in-python-b68fd390b219">Chatbot In Python</a></p></blockquote><blockquote id="6d5e"><p>6. <a href="https://readmedium.com/collections-in-python-d0bc0ed8d938">Python Collections</a></p></blockquote><blockquote id="f7d2"><p>7. <a href="https://readmedium.com/python-modules-abb0145a5963">Python Modules</a></p></blockquote><blockquote id="31fb"><p>8. <a href="https://readmedium.com/python-developer-skills-371583a69be1">Python developer Skills</a></p></blockquote><blockquote id="c1b2"><p>9. <a href="https://readmedium.com/oops-interview-questions-621fc922cdf4">OOPs Interview Questions and Answers</a></p></blockquote><blockquote id="fb28"><p>10. <a href="https://readmedium.com/python-developer-resume-ded7799b4389">Resume For A Python Developer</a></p></blockquote><blockquote id="6254"><p>11. <a href="https://readmedium.com/exploratory-data-analysis-in-python-3ee69362a46e">Exploratory Data Analysis In Python</a></p></blockquote><blockquote id="9e9b"><p>12. <a href="https://readmedium.com/python-turtle-module-361816449390">Snake Game With Python’s Turtle Module</a></p></blockquote><blockquote id="eb94"><p>13. <a href="https://readmedium.com/python-developer-salary-ba2eff6a502e">Python Developer Salary</a></p></blockquote><blockquote id="3529"><p>14.<a href="https://readmedium.com/principal-component-analysis-69d7a4babc96"> Principal Component Analysis</a></p></blockquote><blockquote id="40c5"><p>15. <a href="https://readmedium.com/python-vs-cpp-c3ffbea01eec">Python vs C++</a></p></blockquote><blockquote id="15fe"><p>16. <a href="https://readmedium.com/scrapy-tutorial-5584517658fb">Scrapy Tutorial</a></p></blockquote><blockquote id="c6b5"><p>17. <a href="https://readmedium.com/scipy-tutorial-38723361ba4b">Python SciPy</a></p></blockquote><blockquote id="a6b0"><p>18. <a href="https://readmedium.com/least-square-regression-40b59cca8ea7">Least Squares Regression Method</a></p></blockquote><blockquote id="9e21"><p>19. <a href="https://readmedium.com/jupyter-notebook-cheat-sheet-88f60d1aca7">Jupyter Notebook Cheat Sheet</a></p></blockquote><blockquote id="bb58"><p>20. <a href="https://readmedium.com/python-basics-f371d7fc0054">Python Basics</a></p></blockquote><blockquote id="1452"><p>21. <a href="https://readmedium.com/python-pattern-programs-75e1e764a42f">Python Pattern Programs</a></p></blockquote><blockquote id="7dd1"><p>22.<i> <a href="https://readmedium.com/web-scraping-with-python-d9e6506007bf"></a></i><a href="https://readmedium.com/web-scraping-with-python-d9e6506007bf">Web Scraping With Python</a></p></blockquote><blockquote id="5d5a"><p>23. <a href="https://readmedium.com/python-decorator-tutorial-bf7b21278564">Python Decorator</a></p></blockquote><blockquote id="4817"><p>24.<a href="https://readmedium.com/spyder-ide-2a91caac4e46"> Python Spyder IDE</a></p></blockquote><blockquote id="e1a5"><p>25. <a href="https://readmedium.com/kivy-tutorial-9a0f02fe53f5">Mobile Applications Using Kivy In Python</a></p></blockquote><blockquote id="8b6e"><p>26. <a href="https://readmedium.com/best-books-for-python-11137561beb7">Top 10 Best Books To Learn &amp; Practice Python</a></p></blockquote><blockquote id="be8e"><p>27. <a href="https://readmedium.com/robot-framework-tutorial-f8a75ab23cfd">Robot Framework With Python</a></p></blockquote><blockquote id="f7ce"><p>28. <a href="https://readmedium.com/snake-game-with-pygame-497f1683eeaa">Snake Game in Python using PyGame</a></p></blockquote><blockquote id="3154"><p>29. <a href="https://readmedium.com/django-interview-questions-a4df7bfeb7e8">Django Interview Questions and Answers</a></p></blockquote><blockquote id="3a33"><p>30. <a href="https://readmedium.com/python-applications-18b780d64f3b">Top 10 Python Applications</a></p></blockquote><blockquote id="8744"><p>31. <a href="https://readmedium.com/hash-tables-and-hashmaps-in-python-3bd7fc1b00b4">Hash Tables and Hashmaps in Python</a></p></blockquote><blockquote id="e084"><p>32. <a href="https://readmedium.com/whats-new-python-3-8-7d52cda747b">Python 3.8</a></p></blockquote><blockquote id="8ed4"><p>33. <a href="https://readmedium.com/support-vector-machine-in-python-539dca55c26a">Support Vector Machine</a></p></blockquote><blockquote id="8ce2"><p>34. <a href="https://readmedium.com/python-tutorial-be1b3d015745">Python Tutorial</a></p></blockquote><p id="c1c6"><i>Originally published at <a href="https://www.edureka.co/blog/generators-in-python/">https://www.edureka.co</a> on July 15, 2019.</i></p></article></body>

What are Generators in Python and how to use them?

Generators in Python — Edureka

Generating iterables or objects that allow stepping over them is considered to be a burdensome task. But, in Python, the implementation of this painful task just gets really smooth. So let’s go ahead and take a closer look at Generators in Python.

Here is a list of all the topics covered in this article:

  • What are the Generators?
  • Advantages of using Generators
  • Normal Functions vs Generator Functions
  • Using Generator Functions
  • Generators with loops
  • Generator Expressions
  • Use Cases
  1. Generating Fibonacci Series
  2. Generating Numbers

So let’s begin. :)

What are Generators in Python?

Generators are basically functions that return traversable objects or items. These functions do not produce all the items at once, rather they produce them one at a time and only when required. Whenever the for statement is included to iterate over a set of items, a generator function is run. Generators have a number of advantages as well.

Advantages of using Generators

  • Without Generators in Python, producing iterables is extremely difficult and lengthy.
  • Generators easy to implement as they automatically implement __iter__(), __next__(), and StopIteration which otherwise, need to be explicitly specified.
  • Memory is saved as the items are produced when required, unlike normal Python functions. This fact becomes very important when you need to create a huge number of iterators. This is also considered as the biggest advantage of generators.
  • Can be used to produce an infinite number of items.
  • They can also be used to pipeline a number of operations

Normal Functions vs Generator Functions:

Generators in Python are created just like how you create normal functions using the ‘def’ keyword. But, Generator functions make use of the yield keyword instead of return. This is done to notify the interpreter that this is an iterator. Not just this, Generator functions are run when the next() function is called and not by their name as in the case of normal functions. Consider the following example to understand it better:

EXAMPLE:

def func(a):
    yield a
a=[1,2,3]
 
b=func(a)
next(b)

OUTPUT: [1, 2, 3]

As you can see, in the above output, func() is making use of the yield keyword and the next function for its execution. But, for normal function you will need the following piece of code:

EXAMPLE:

def func(a):
    return a
a=[1,2,3]
func(a)

OUTPUT: [1, 2, 3]

If you look at the above example, you might be wondering why to use a Generator function when the normal function is also returning the same output. So let’s move on and see how to use Generators in Python.

Using Generator functions:

As mentioned earlier, Generators in Python produce iterables one at a time. Take a look at the following example:

EXAMPLE:

def myfunc(a):
    while a>=3:
        yield a
        a=a+1
b =  myfunc(a)
print(b)
next(b)

When you execute the following function, you will see the following output:

OUTPUT: 4

Here, one iterable object has been returned satisfying the while condition. After execution, the control is transferred to the caller. In case more items are needed, the same function needs to be executed again by calling the next() function.

next(b)

OUTPUT: 5

On further executions, the function will return 6,7, etc. Generator functions in Python implement the __iter__() and __next__() methods automatically. Therefore, you can iterate over the objects by just using the next() method. When the item generation should terminate, Generator functions implement the StopIteration internally without having to worry the caller. Here is another example of this:

EXAMPLE:

a=2
def myfunc(a):
    while a >= 0:
        yield a
        a -= 1
b =  myfunc(a)
print(b)
next(b)

OUTPUT:

The above image shows the execution of our program required a number of times. If you try to call the next function again, it returns a message depicting StopIteration has been implemented. If you try to do this with normal functions, the values returned will not change or iterate. Take a look at the example below:

EXAMPLE:

def z():
    n=1
    yield n
    n=n+3
    yield n
p=z()
next(p)

OUTPUT:

Generators with loops:

In case you want to execute the same function at once, you can make use of the ‘for’ loop. This loop helps iterate over the objects and after all implementations it executes StopIteration.

EXAMPLE:

def z():
    n=1
    yield n
    n=n+3
    yield n
for x in z():
    print(x)

OUTPUT:

1 4

You can also specify expressions to generate iterable objects.

Generator Expressions:

You can also use expressions along with the for loop to produce iterators. This usually makes the generation iterables much easy. Generator expression resemble list comprehensions and like lambda functions, generator expressions create anonymous generator functions.

Take a look at the example below:

EXAMPLE:

a=range(6)
print("List Comprehension", end=':')
b=[x+2 for x in a] 
print(b)
print("Generator expression", end=':n')
c=(x+2 for x in a) 
print(c)
for y in c:
    print(y)

OUTPUT:

List Comprehension:[2, 3, 4, 5, 6, 7]

Generator expression:

at 0x0000016362944480>

2 3 4 5 6

As you can see, in the above output, the first expression is a list comprehension which is specified within [] brackets. List comprehension produces the complete list of items at once. The next is a generator expression that returns the same items but one at a time. It is specified using () brackets.

Generator functions can be used within other functions as well. For example:

EXAMPLE:

a=range(6)
print("Generator expression", end=':n')
c=(x+2 for x in a) 
print(c)
print(min(c))

OUTPUT:

Generator expression 2

The above program prints the min value when the above expression as applied to the values of a.

Use Cases:

Let us use Generators in Python to:

  • Generate Fibonacci Series
  • Generating Numbers

Generating Fibonacci Series:

Fibonacci series as we all know is a series of numbers wherein each number is a sum of preceding two numbers. The first two numbers are 0 and 1. Here is a generator program to generate Fibonacci series:

EXAMPLE:

def fibo():
    first,second=0,1
    while True:
        yield first
        first,second=second,first+second
for x in fibo():
    if x>50:
        break
    print(x, end=" ")

OUTPUT:

0 1 1 2 3 5 8 13 21 34

The above output shows the Fibonacci series with values less than 50. Let’s now take a look at how to generate a list of numbers.

Generating Numbers:

In case you want to generate specified list numbers, you can do it using generator functions. Take a look a look at the following example:

EXAMPLE:

a=range(10)
b=(x for x in a) 
print(b)
for y in b:
    print(y)

OUTPUT:

at 0x000001CBE1602DE0>

0 1 2 3 4 5 6 7 8 9

EXAMPLE:

a=range(2,10,2)
b=(x for x in a) 
print(b)
for y in b:
    print(y)

OUTPUT:

at 0x000001CBE1623138> 2 4 6 8

The above program has returned even numbers from 2 to 10. This brings us to the end of this article on Generators in Python. I hope you have understood all the topics.

Make sure you practice as much as possible and revert your experience.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

1. Machine Learning Classifier in Python

2. Python Scikit-Learn Cheat Sheet

3. Machine Learning Tools

4. Python Libraries For Data Science And Machine Learning

5. Chatbot In Python

6. Python Collections

7. Python Modules

8. Python developer Skills

9. OOPs Interview Questions and Answers

10. Resume For A Python Developer

11. Exploratory Data Analysis In Python

12. Snake Game With Python’s Turtle Module

13. Python Developer Salary

14. Principal Component Analysis

15. Python vs C++

16. Scrapy Tutorial

17. Python SciPy

18. Least Squares Regression Method

19. Jupyter Notebook Cheat Sheet

20. Python Basics

21. Python Pattern Programs

22. Web Scraping With Python

23. Python Decorator

24. Python Spyder IDE

25. Mobile Applications Using Kivy In Python

26. Top 10 Best Books To Learn & Practice Python

27. Robot Framework With Python

28. Snake Game in Python using PyGame

29. Django Interview Questions and Answers

30. Top 10 Python Applications

31. Hash Tables and Hashmaps in Python

32. Python 3.8

33. Support Vector Machine

34. Python Tutorial

Originally published at https://www.edureka.co on July 15, 2019.

Python
Python3
Generators In Python
Python Programming
Programming
Recommended from ReadMedium
avatarAbhay Kumar
OOPs in Python

An easy guide

10 min read