Info
Open the page on your phone

What is the difference between iterators and generators?

Iterators are objects in Python that represent a stream of data, and they implement the __iter__ and __next__ methods. They allow iteration over a sequence of elements. Generators, on the other hand, are a special kind of iterator which are created using a function that contains one or more yield expressions. Generators can pause and resume execution, allowing for the generation of a sequence of values over time, as opposed to generating all the values at once.

                        
Example:

# Iterator example
iter_obj = iter([1, 2, 3])
print(next(iter_obj))  # Output: 1
print(next(iter_obj))  # Output: 2

# Generator example

# The following function is a generator function
def my_generator():
    yield 1
    yield 2
    yield 3

gen_obj = my_generator()
print(next(gen_obj))  # Output: 1
print(next(gen_obj))  # Output: 2