Saturday, 29 April 2023

Return VS Yield in Python


In Python, return and yield are two ways to send a value back from a function or generator to its caller, but they work in different ways.

return is a statement that immediately terminates the execution of a function and returns a value to the caller. When the function is called again, it starts executing from the beginning.

Here's an example:

def square(x):

    return x * x

result = square(5)

print(result)  # Output: 25

In this example, the square() function takes an argument x and returns its square using the return statement.

On the other hand, yield is a keyword that allows a function to return a generator object, which can be used to iterate over a sequence of values. When the function is called, it executes until it reaches a yield statement, which returns a value to the caller and suspends the function's execution. The next time the function is called, it continues executing from where it left off until it reaches another yield statement or the end of the function.

Here's an example:

def squares(n):
    for i in range(n):
        yield i * i

result = squares(5)
for square in result:
    print(square)  # Output: 0 1 4 9 16

In this example, the squares() function generates a sequence of squares using a for loop and the yield statement. The result variable holds a generator object, which is then iterated over using a for loop to print the squares.

In summary, return is used to immediately terminate a function and return a value to the caller, while yield is used to create a generator object that can be iterated over to return a sequence of values one at a time.


Post a Comment

Codecademy Code Foundations

Popular Posts


Android (23) AngularJS (1) Assembly Language (2) Books (10) C (75) C# (12) C++ (81) Course (1) Data Strucures (4) Downloads (1) Engineering (13) flutter (1) FPL (17) Hadoop (1) HTML&CSS (40) IS (25) Java (89) Leet Code (4) Pandas (1) PHP (20) Projects (19) Python (423) R (69) Selenium Webdriver (2) Software (14) SQL (27)