Generators and Generator Expressions
Generators and Generator Expressions
expressions)
This lazy evalua on can be very efficient, especially for large datasets or infinite sequences.
Generators
A generator is a special type of iterator that is defined using a func on that contains one or more yield
statements. When a generator func on is called, it returns an iterator object but does not start execu on
immediately.
Instead, the code inside the func on is paused at each yield statement, and the value specified a er the
yield is returned to the caller. The state of the generator func on is preserved between calls, allowing it to
resume execu on where it le off.
def countdown(n):
while n > 0:
yield n
n -= 1
In this example, the countdown func on is a generator that yields numbers from n down to 1. Each me
the yield statement is encountered, the func on pauses and returns the current value of n to the caller.
Generator Expressions
Generator expressions provide a more concise way to create simple generators without the need for a
separate func on defini on. They have a syntax similar to list comprehensions but use parentheses
instead of square brackets.
1
NANOEDGE INTERNATIONAL – PYTHON PROGRAMMING COURSE (Generators and Generator
expressions)
Generator expressions are par cularly useful when you need to generate a sequence of values on the fly
without storing them in memory.
In this example, the generator expression (x**2 for x in range(1, 6)) generates the squares of numbers
from 1 to 5. Each value is produced lazily when needed, allowing for efficient memory usage.
iter() func on
The iter() func on is used to create an iterator from an iterable object. When called with an iterable, such
as a list or a generator, it returns an iterator object that can be used to traverse the elements of the
iterable.
next() func on
The next() func on is used to retrieve the next element from an iterator. When called, it returns the next
element in the iterator's sequence. If there are no more elements in the sequence, it raises a StopItera on
excep on.
2
NANOEDGE INTERNATIONAL – PYTHON PROGRAMMING COURSE (Generators and Generator
expressions)
n -= 1
Addi onally, if we try to call next() beyond the end of the iterator, it will raise a StopItera on excep on.
print(next(iterator))