The Python, yield keyword is used to create a generator function. A type of function that is memory efficient and can be used like an iterator object. It is a case-sensitive keyword. In a function, it returns an expression or object
The yield statement of a function returns a generator object rather than just returning a value to the call of the function that contains the statement.
SyntaxFollowing is a syntax of the Python yield keyword −
def fun_name(): statements yield expressionExample
Following is a basic example of the Python yield keyword −
#defined generator def fun1(): yield "Hello" yield "Welcome" yield "To" yield "Tutorialspoint" result_1 = fun1() print(type(result_1)) #iterating through generator for i in result_1: print(i)Output
Following is the output of the above code −
<class 'generator'> Hello Welcome To TutorialspointUsing yield with tuple
The yield keyword returns a iterables like tuple, list, set etc..
ExampleHere, we have created a generator named even which will return a even numbers in the form of tuple −
def even(n): for i in range(n): if i%2==0: yield i even_num = even(20) print(tuple(even_num))
Output
Following is the output of the above code −
(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)Difference between yield and return
In Python, return and yield are both used to send values from a function, but they operate differently. The return exits the function and sends back a single value or object, immediately terminating the function's execution. whereas the yield is used in a generator function to pause the function's execution and send back a value, allowing the function to resume where it left off the next time it's called. This makes yield ideal for generating a sequence of values over time, while return is used for a single result or when the function needs to end.
ExampleHere, we have defined both function and generator. The function return the a single value whereas, the generator returned a list of element −
#defined a function def power(n): return n**2 #defined a generator def power_1(n): for i in range(n): yield i**2 result_1 = power(4) result_2 = (list(power_1(4))) print("Return :", result_1) print("Yield :", result_2)
Output
Following is the output of the above code −
Return : 16 Yield : [0, 1, 4, 9]
python_keywords.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4