Using generator function in Python

0 votes
As I come from a Java background, is there a Java equivalent of generator? 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 29, 2018 in Python by findingbugs
• 3,140 points

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

A generator is effectively a function that returns (data) before it is finished, but it pauses at that point, and you can resume the function at that point.

>>> def myGenerator():
...     yield 'These'
...     yield 'words'
...     yield 'come'
...     yield 'one'
...     yield 'at'
...     yield 'a'
...     yield 'time'

>>> myGeneratorInstance = myGenerator()
>>> next(myGeneratorInstance)
>>> next(myGeneratorInstance)

and so on. The (or one) benefit of generators is that because they deal with data one piece at a time, you can deal with large amounts of data; with lists, excessive memory requirements could become a problem. Generators, just like lists, are iterable, so they can be used in the same ways:

>>> for word in myGeneratorInstance:
...     print word
answered Oct 29, 2018 by Priyaj
• 56,140 points

Related Questions In Python

0 votes
1 answer

How to print objects of class using print function in Python?

It can be done as shown below: class Element: ...READ MORE

answered Dec 3, 2018 in Python by Nymeria
• 3,500 points

edited Dec 19, 2018 by Nymeria 106 views
0 votes
1 answer

What is the use of raw_input function in Python?

raw_input fuction is no longer available in ...READ MORE

answered May 2, 2018 in Python by aayushi
• 750 points
0 votes
1 answer

Using quotes in python

Both the conventions for enclosing strings are ...READ MORE

answered May 9, 2018 in Python by Nietzsche's daemon
• 4,260 points
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
+2 votes
3 answers

How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,710 points
+1 vote
1 answer

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.