Sunday, 30 April 2023

What does the “yield” keyword do in python?

 In Python, the yield keyword is used to create a generator function. When a function includes a yield statement, it becomes a generator function, which returns an iterator object that can be iterated over with a loop.

The yield statement suspends the function's execution and sends a value back to the caller, but unlike return, the function state is saved, and the function can be resumed later from where it left off.

Here's an example to demonstrate the use of yield:

def countdown(num):

    while num > 0:

        yield num

        num -= 1

This generator function countdown() will return an iterator that will produce a sequence of numbers from num down to 1. We can use a for loop to iterate over the sequence:

for i in countdown(5):


Each time the yield statement is reached, the function's state is saved, and the value of num is sent back to the caller. The next time the generator is called, execution continues from where it left off, and num is decremented until it reaches zero.


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)