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.

0 Comments:

Post a Comment

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (117) C (77) C# (12) C++ (82) Course (62) Coursera (179) coursewra (1) Cybersecurity (22) data management (11) Data Science (95) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (748) Python Coding Challenge (221) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses