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,870 points
40 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,160 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
• 56,520 points
22 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
• 56,520 points
682 views
0 votes
1 answer

What are generators in Python?

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

answered Jul 11 in Python by Neel
• 3,010 points
19 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,810 points
133 views
+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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 232 views
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,160 points
242 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,160 points
34 views