Python Generators
In Python, a generator is a function or expression that will process a given iterable one object at a time, on demand. A generator will return a generator object, which can be cast as a list or some other data structure as appropriate.
Generators
Generators are a convenient means of employing iterator functionality within the syntax of a function or expression. One of the main advantages of generators is that they evaluate items on demand, which means only one item is in memory at a time in lieu of the entire sequence (as with a list).
A Generator Function
The following code shows the creation of a generator function. In the function definition, the yield statement is used to return or include an item in the final generator object.
def return_evens(lst):for l in lst:if l % 2 == 0:yield leggs = [x for x in range(20)]print(list(return_evens(eggs)))# Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
A Generator Expression
The functionality in the previous example can alternatively be defined as an expression. A generator expression utilizes the same syntax as a list comprehension with parentheses framing the statement instead of square brackets.
eggs = [x for x in range(20)] # a list comprehensionlist((x for x in eggs if x % 2 == 0)) # a generator expression
Custom Iteration
A generator object can be incrementally advanced with the next() function. When next() is called the current item is returned and the state is saved.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours