Note: this post assumes Python 3.x syntax.†

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, thus:

>>> for n in myGen(6):
...     print(n)
... 
6
7

Likewise there are generator expressions, which provide a means to succinctly describe certain common types of generators:

>>> g = (n for n in range(3, 5))
>>> next(g)
3
>>> next(g)
4
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Note that generator expressions are much like list comprehensions:

>>> lc = [n for n in range(3, 5)]
>>> lc
[3, 4]

Observe that a generator object is generated once, but its code is not run all at once. Only calls to next actually execute (part of) the code. Execution of the code in a generator stops once a yield statement has been reached, upon which it returns a value. The next call to next then causes execution to continue in the state in which the generator was left after the last yield. This is a fundamental difference with regular functions: those always start execution at the "top" and discard their state upon returning a value.

There are more things to be said about this subject. It is e.g. possible to send data back into a generator (reference). But that is something I suggest you do not look into until you understand the basic concept of a generator.

Now you may ask: why use generators? There are a couple of good reasons:

  • Certain concepts can be described much more succinctly using generators.
  • Instead of creating a function which returns a list of values, one can write a generator which generates the values on the fly. This means that no list needs to be constructed, meaning that the resulting code is more memory efficient. In this way one can even describe data streams which would simply be too large to fit in memory.
  • Generators allow for a natural way to describe infinite streams. Consider for example the Fibonacci numbers:

    >>> def fib():
    ...     a, b = 0, 1
    ...     while True:
    ...         yield a
    ...         a, b = b, a + b
    ... 
    >>> import itertools
    >>> list(itertools.islice(fib(), 10))
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
    

    This code uses itertools.islice to take a finite number of elements from an infinite stream. You are advised to have a good look at the functions in the itertools module, as they are essential tools for writing advanced generators with great ease.


  † About Python <=2.6: in the above examples next is a function which calls the method __next__ on the given object. In Python <=2.6 one uses a slightly different technique, namely o.next() instead of next(o). Python 2.7 has next() call .next so you need not use the following in 2.7:

>>> g = (n for n in range(3, 5))
>>> g.next()
3
Answer from Stephan202 on Stack Overflow
🌐
Online Python
online-python.com
Online Python - IDE, Editor, Compiler, Interpreter
This tool can be used to learn, build, run, test your python script. You can open the script from your local and continue to build using this IDE. Code and output can be downloaded to local. Code can be saved online using the "share" option which enables to access the code anytime, anywhere ...
🌐
Programiz
programiz.com › python-programming › online-compiler
Online Python Compiler (Editor)
Learn Python · main.py Output · Visualize · Share Download New Contact us Dark mode Light mode · main.py · Visualize Run · # Online Python compiler (interpreter) # Write and run Python online using this editor. print("What does the Visualize button do?") Visualize Run ·
🌐
W3Schools
w3schools.com › python › python_generators.asp
Python Generators
Generators are functions that can pause and resume their execution.
🌐
GeeksforGeeks
geeksforgeeks.org › python › generators-in-python
Generators in Python - GeeksforGeeks
Instead of using return to send back a single value, generator functions use yield to produce a series of results over time. The function pauses its execution after yield, maintaining its state between iterations. Python · def fun(max): cnt = 1 while cnt <= max: yield cnt cnt += 1 ctr = fun(5) for n in ctr: print(n) Output ·
Published: December 12, 2025
Top answer
1 of 13
497

Note: this post assumes Python 3.x syntax.†

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, thus:

>>> for n in myGen(6):
...     print(n)
... 
6
7

Likewise there are generator expressions, which provide a means to succinctly describe certain common types of generators:

>>> g = (n for n in range(3, 5))
>>> next(g)
3
>>> next(g)
4
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Note that generator expressions are much like list comprehensions:

>>> lc = [n for n in range(3, 5)]
>>> lc
[3, 4]

Observe that a generator object is generated once, but its code is not run all at once. Only calls to next actually execute (part of) the code. Execution of the code in a generator stops once a yield statement has been reached, upon which it returns a value. The next call to next then causes execution to continue in the state in which the generator was left after the last yield. This is a fundamental difference with regular functions: those always start execution at the "top" and discard their state upon returning a value.

There are more things to be said about this subject. It is e.g. possible to send data back into a generator (reference). But that is something I suggest you do not look into until you understand the basic concept of a generator.

Now you may ask: why use generators? There are a couple of good reasons:

  • Certain concepts can be described much more succinctly using generators.
  • Instead of creating a function which returns a list of values, one can write a generator which generates the values on the fly. This means that no list needs to be constructed, meaning that the resulting code is more memory efficient. In this way one can even describe data streams which would simply be too large to fit in memory.
  • Generators allow for a natural way to describe infinite streams. Consider for example the Fibonacci numbers:

    >>> def fib():
    ...     a, b = 0, 1
    ...     while True:
    ...         yield a
    ...         a, b = b, a + b
    ... 
    >>> import itertools
    >>> list(itertools.islice(fib(), 10))
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
    

    This code uses itertools.islice to take a finite number of elements from an infinite stream. You are advised to have a good look at the functions in the itertools module, as they are essential tools for writing advanced generators with great ease.


  † About Python <=2.6: in the above examples next is a function which calls the method __next__ on the given object. In Python <=2.6 one uses a slightly different technique, namely o.next() instead of next(o). Python 2.7 has next() call .next so you need not use the following in 2.7:

>>> g = (n for n in range(3, 5))
>>> g.next()
3
2 of 13
62

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)
These
>>> next(myGeneratorInstance)
words

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
These
words
come
one
at 
a 
time

Note that generators provide another way to deal with infinity, for example

>>> from time import gmtime, strftime
>>> def myGen():
...     while True:
...         yield strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())    
>>> myGeneratorInstance = myGen()
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:17:15 +0000
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:18:02 +0000   

The generator encapsulates an infinite loop, but this isn't a problem because you only get each answer every time you ask for it.

🌐
Mimo
mimo.org › glossary › python › generator
Python Generator: Syntax, Usage, and Examples
Start your coding journey with Python. Learn basics, data types, control flow, and more ... # Basic generator function def count_up_to(n): count = 1 while count <= n: yield count # Yield the current count value count += 1 # Using the generator counter = count_up_to(5) for num in counter: print(num)
🌐
Python Online
pythononline.net
Python Online - Editor, Compiler, Interpreter, IDE
Clear the Output panel before each code execution. ... Auto-format code when saving. ... Render specialized symbols (e.g., '!=' becomes '≠'). ... Show autocompletion as you type. ... Show documentation when hovering over code. ... Show argument details while typing functions. ... Highlight other occurrences of selected strings, variables, etc. ... Enable IntelliSense for HTML/CSS. Disable to improve load time. ... Analyze code for errors (Python, JS, JSON).
🌐
OneCompiler
onecompiler.com › python
Python Online Compiler & Interpreter
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab.
Find elsewhere
🌐
Python
python.org › about › success › cog
Cog: A Code Generation Tool Written in Python
Cog reads a text file (C++ in our case), looking for specially-marked sections of text, that it will use as generators. It executes those sections as Python code, capturing the output.
🌐
Python
wiki.python.org › moin › Generators
Generators
Both range and xrange represent a range of numbers, and have the same function signature, but range returns a list while xrange returns a generator (at least in concept; the implementation may differ). Say, we had to compute the sum of the first n, say 1,000,000, non-negative numbers. 1 # Note: Python 2.x only 2 # using a non-generator 3 sum_of_first_n = sum(range(1000000)) 4 5 # using a generator 6 sum_of_first_n = sum(xrange(1000000))
Top answer
1 of 8
220

Quick answer:

Doing list() around a generator expression is (almost) exactly equivalent to having [] brackets around it. So yeah, you can do

>>> list((x for x in string.letters if x in (y for y in "BigMan on campus")))

But you can just as well do

>>> [x for x in string.letters if x in (y for y in "BigMan on campus")]

Yes, that will turn the generator expression into a list comprehension. It's the same thing and calling list() on it. So the way to make a generator expression into a list is to put brackets around it.

In Python 3, you could unpack the generator expression into a print statement:

>>> print(*(x for x in string.ascii_letters if x in (y for y in "BigMan on campus")))
a c g i m n o p s u B M

Detailed explanation:

A generator expression is a "naked" for expression. Like so:

x*x for x in range(10)

Now, you can't stick that on a line by itself, you'll get a syntax error. But you can put parenthesis around it.

>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7485464>

This is sometimes called a generator comprehension, although I think the official name still is generator expression, there isn't really any difference, the parenthesis are only there to make the syntax valid. You do not need them if you are passing it in as the only parameter to a function for example:

>>> sorted(x*x for x in range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Basically all the other comprehensions available in Python 3 and Python 2.7 is just syntactic sugar around a generator expression. Set comprehensions:

>>> {x*x for x in range(10)}
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}

>>> set(x*x for x in range(10))
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}

Dict comprehensions:

>>> dict((x, x*x) for x in range(10))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

>>> {x: x*x for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

And list comprehensions under Python 3:

>>> list(x*x for x in range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Under Python 2, list comprehensions is not just syntactic sugar. But the only difference is that x will under Python 2 leak into the namespace.

>>> x
9

While under Python 3 you'll get

>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

This means that the best way to get a nice printout of the content of your generator expression in Python is to make a list comprehension out of it! However, this will obviously not work if you already have a generator object. Doing that will just make a list of one generator:

>>> foo = (x*x for x in range(10))
>>> [foo]
[<generator object <genexpr> at 0xb7559504>]

In that case you will need to call list():

>>> list(foo)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Although this works, but is kinda stupid:

>>> [x for x in foo]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2 of 8
23

Or you can always map over an iterator, without the need to build an intermediate list:

>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM
🌐
Learn Python
learnpython.org › en › Generators
Generators - Learn Python - Free Interactive Python Tutorial
# testing code import types if type(fib()) == types.GeneratorType: print("Good, The fib function is a generator.") counter = 0 for n in fib(): print(n) counter += 1 if counter == 10: break # fill in this function def fib(): a, b = 1, 1 while 1: yield a a, b = b, a + b # testing code import types if type(fib()) == types.GeneratorType: print("Good, The fib function is a generator.") counter = 0 for n in fib(): print(n) counter += 1 if counter == 10: break test_output_contains("Good, The fib function is a generator.") success_msg('Good work!') This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-print-a-generator-expression
How To Print A Generator Expression? - Python
January 25, 2024 - Printing the results of a generator expression in Python can be accomplished in various ways, each with its own advantages. Choose the method that best suits your requirements, balancing factors like memory efficiency, readability, and simplicity. Whether using a for loop, converting to a list, employing the print function with *, joining with str.join, or utilizing the itertools module, these methods provide flexibility in displaying the output ...
🌐
KDnuggets
kdnuggets.com › 2023 › 02 › getting-started-python-generators.html
Getting Started with Python Generators - KDnuggets
February 27, 2023 - ... If you print out the value of cubes_gen(), you’ll get a generator object as opposed to the entire resultant list that contains the cube of each of the numbers. Output >> <generator ...
🌐
Toppr
toppr.com › guides › python-guide › tutorials › python-advanced-topics › python-yield-generators-and-generator-expressions
Python Yield, Generators and Generator Expressions | Python Generators |
November 5, 2021 - To print the actual output, we must feed the object instance to the next() function. The major difference between an ordinary function and a generator function is that the state of generator functions is maintained by utilizing the keyword yield, which works similarly to using return but with some important changes.
🌐
SQLPad
sqlpad.io › home › blog › introduction to python generators
Introduction to python generators | SQLPad
April 29, 2024 - def data_processor(): while True: try: data = yield print(f"Processed {data}") except Exception as e: print(f"Exception caught: {e}") gen = data_processor() next(gen) # Required to start the generator gen.send(10) # Output: Processed 10 gen.throw(ValueError, "Invalid value") # Output: Exception caught: Invalid value · It's essential to use exception handling within the generator to ensure graceful degradation of your application. By understanding these pitfalls and learning how to avoid them, you can write more robust and reliable code using Python generators.
🌐
LabEx
labex.io › tutorials › python-how-to-control-generator-output-438205
How to control generator output | LabEx
Generators in Python are a powerful way to create iterators. Unlike traditional functions that return a complete result at once, generators yield values one at a time, making them memory-efficient and ideal for handling large datasets.
🌐
Medium
medium.com › @vivekvjnk › understanding-python-generators-the-power-of-yield-and-state-management-382faa48e761
Understanding Python Generators : The Power of “yield” and State Management | by Story_Teller | Medium
October 20, 2024 - In addition to generator functions, Python provides generator expressions, which are similar to list comprehensions but use parentheses () instead of square brackets []. These provide a concise way to create generators.
🌐
Hero Vired
herovired.com › learning-hub › blogs › generators-in-python
Generators in Python with Examples 2025 | Hero Vired
January 21, 2025 - As you can see, generators provide an easy and efficient way to produce a sequence of values. ... Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems. ... Python Generators are more efficient than loops for large datasets, as they produce values one by one instead of storing them in memory before returning them.