WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Intermediate · question 25 of 100

What is a generator in Python, and how do you create one? What are its advantages over a list?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

In Python, a generator is a special type of iterable, similar to a list or a tuple, that allows for lazy evaluation of its elements. Instead of generating all the elements at once, a generator generates one element at a time as requested. This can be useful for large datasets or when working with infinite sequences.

A generator is created using a generator function, which is a function that contains the yield keyword. The yield keyword is used to return a value from the function, while also temporarily suspending the function’s execution. When the generator is iterated over, the function is resumed from where it left off, and the next value is returned.

Here’s an example of a generator function that generates the first n even numbers:

    def even_numbers(n):
        for i in range(n):
        yield 2*i
    
    # Creating a generator object
    even_gen = even_numbers(5)
    
    # Iterating over the generator
    for num in even_gen:
        print(num)
    
    # Output: 0 2 4 6 8

The advantages of using a generator over a list include:

Memory efficiency: Generators generate elements on the fly, which means that only one element is in memory at a time. This can be useful when working with large datasets or infinite sequences, where storing all the elements in memory at once would be impractical.

Performance: Generators can be faster than creating a list, especially for large datasets, because they generate elements on the fly instead of storing them all in memory at once.

Lazy evaluation: Generators allow for lazy evaluation of elements, which means that elements are only generated when they are needed. This can be useful when working with infinite sequences or when processing large datasets, because it allows you to generate only the elements that are needed at a given time.

In summary, a generator in Python is a special type of iterable that allows for lazy evaluation of elements. Generators are created using generator functions, which contain the yield keyword. The advantages of using a generator over a list include memory efficiency, performance, and lazy evaluation.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics