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 26 of 100

Can you explain the differences between ’yield’ and ’return’ in Python?

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

In Python, both yield and return are used to return values from a function, but they have different meanings and behaviors.

return is used to return a value from a function and exit the function. When a function encounters a return statement, it immediately exits the function and returns the specified value to the calling code. Any code after the return statement is not executed.

Here’s an example of using return in a function to return the sum of two numbers:

    def sum_numbers(x, y):
        return x + y
    
    result = sum_numbers(3, 4)
    print(result) # Output: 7

On the other hand, yield is used in a generator function to return a value and temporarily suspend 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. This allows generators to generate a sequence of values on the fly, rather than all at once.

Here’s an example of using yield in a generator function to generate a sequence of numbers:

    def sequence_numbers(n):
        for i in range(n):
            yield i
    
    # Creating a generator object
    seq_gen = sequence_numbers(5)
    
    # Iterating over the generator
    for num in seq_gen:
        print(num)
    
    # Output: 0 1 2 3 4

In summary, return is used to exit a function and return a value to the calling code, while yield is used in a generator function to temporarily suspend the function’s execution and return a value to the calling code. The main difference between return and yield is that return exits the function, while yield allows the function to resume its execution from where it left off.

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