What is a Python Generator?

What is a Python Generator?

a) A function that returns an iterator which can iterate over a sequence of values
b) A function that returns multiple values at once
c) A method for creating new objects in Python
d) A module used for generating random numbers

Answer:

a) A function that returns an iterator which can iterate over a sequence of values

Explanation:

A Python generator is a special type of function that returns an iterator, which can be used to iterate over a sequence of values. Generators are defined using the yield keyword, which allows them to produce a series of values lazily, one at a time, without holding the entire sequence in memory.

def simple_generator():
    yield 1
    yield 2
    yield 3

# Using the generator
for value in simple_generator():
    print(value)  # Output: 1, 2, 3

In this example, simple_generator() is a generator function that yields three values, one at a time. When iterated, it produces each value in sequence.

Generators are particularly useful when dealing with large datasets or streams of data, as they allow for efficient memory usage and the ability to handle infinite sequences.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top