Generators are a powerful feature in Python that allow you to create iterators in a more memory-efficient way. They are functions that return an iterable set of items one at a time using the yield keyword. This article will explain how to create and use generators in Python, along with examples.
A generator is a function that behaves like an iterator. Unlike regular functions that return a single value, a generator uses the yield statement to return a value, but it can return multiple values one at a time, each time the generator is called. The state of the generator is preserved between calls, which allows it to resume where it left off.
yield
To create a generator, you define a function that uses the yield
keyword. Each time the generator function is called, it yields a value and pauses its execution, keeping track of the local variables and the position of the execution.
def simple_generator(): yield 1 yield 2 yield 3 gen = simple_generator() # Using the generator for value in gen: print(value)
In this example, the function simple_generator
yields three values (1, 2, and 3). When we iterate over the generator object gen
, each value is yielded one at a time, and the function pauses after each yield
statement.
1 2 3
next()
You can also manually retrieve values from a generator using the next()
function. This allows you to control the flow of the generator and get the next yielded value each time.
next()
with a Generator:gen = simple_generator() print(next(gen)) # Output: 1 print(next(gen)) # Output: 2 print(next(gen)) # Output: 3
In this example, the next()
function retrieves the next value from the generator. When there are no more values to yield, a StopIteration
exception is raised.
1 2 3
Python also supports generator expressions, which provide a compact syntax for creating generators. A generator expression looks like a list comprehension but uses parentheses instead of square brackets.
gen_expr = (x * x for x in range(5)) # Using the generator expression for value in gen_expr: print(value)
In this example, the generator expression (x * x for x in range(5))
creates a generator that yields the squares of numbers from 0 to 4.
0 1 4 9 16
Generators have several advantages over traditional functions that return lists:
Generators in Python are a powerful tool for working with large or infinite sequences of data. By using the yield
keyword, you can create functions that yield values one at a time, saving memory and improving performance. Whether you are processing data in a loop or working with streams of data, generators can simplify your code and make it more efficient.