Understanding generators in Python

0 votes
I am reading the Python cookbook at the moment and am currently looking at generators. I'm finding it hard to get my head round.

As I come from a Java background, is there a Java equivalent? The book was speaking about 'Producer / Consumer', however when I hear that I think of threading.What is a generator and why would you use it?
Oct 26, 2018 in Python by ana1504.k
• 7,910 points
631 views

1 answer to this question.

0 votes
A generator is simply a function which returns an object on which you can call next, such that for every call it returns some value, until it raises a StopIteration exception, signaling that all values have been generated. Such an object is called an iterator.

Normal functions return a single value using return, just like in Java. In Python, however, there is an alternative, called yield. Using yield anywhere in a function makes it a generator. Observe this code:

>>> def myGen(n):
...     yield n
...     yield n + 1
...
>>> g = myGen(6)
>>> next(g)
6
>>> next(g)
7
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
As you can see, myGen(n) is a function which yields n and n + 1. Every call to next yields a single value, until all values have been yielded. for loops call next in the background.
answered Oct 26, 2018 by SDeb
• 13,300 points

Related Questions In Python

+1 vote
1 answer

Understanding Pickling in Python

While others have pointed to the Python ...READ MORE

answered Aug 22, 2018 in Python by Priyaj
• 58,020 points
937 views
0 votes
1 answer

Understanding repr( ) function in Python

>>> x = 'foo' >>> x 'foo' So the name x is ...READ MORE

answered Sep 17, 2018 in Python by Priyaj
• 58,020 points
6,185 views
0 votes
1 answer

What are generators in Python?

There are two terms involved when we ...READ MORE

answered Jul 11, 2019 in Python by Neel
• 3,020 points
726 views
+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,890 points
20,009 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
0 votes
1 answer

Indentation of Python in Notepad++

To indent the block, select the entire ...READ MORE

answered Sep 18, 2018 in Python by SDeb
• 13,300 points
2,350 views
0 votes
1 answer

Print C format in Python

For printf- style formatting and special case ...READ MORE

answered Sep 18, 2018 in Python by SDeb
• 13,300 points
1,005 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP