{"id":1657,"date":"2024-03-05T13:24:55","date_gmt":"2024-03-05T07:54:55","guid":{"rendered":"https:\/\/geekpython.in\/?p=1657"},"modified":"2024-03-28T16:43:27","modified_gmt":"2024-03-28T11:13:27","slug":"yield-keyword-in-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/yield-keyword-in-python","title":{"rendered":"Yield Keyword in Python with Examples"},"content":{"rendered":"\n<p>To return a value from a Python function, you must have used the <code>return<\/code> keyword. When the program encounters the <code>return<\/code> keyword, it exits the function and returns the value to the caller before proceeding to execute additional code.<\/p>\n\n\n\n<p>However, the case is entirely different with the <code>yield<\/code> keyword. It does control the flow of execution and returns a value like the <code>return<\/code> keyword but how it behaves is different.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">yield Keyword<\/h2>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<p class=\"responsive-video-wrap clr\"><iframe loading=\"lazy\" title=\"Python Yield Keyword?? 2MinutesPy\" width=\"1200\" height=\"675\" src=\"https:\/\/www.youtube.com\/embed\/xZJNa71Rvt4?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<\/div><\/figure>\n\n\n\n<p>When a function contains a <code>yield<\/code> statement, it is considered a <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/python-generators-with-yield-statement\">generator function<\/a>. <strong>The <\/strong><code>yield<\/code> <strong>keyword alters the behavior of the function. How?<\/strong><\/p>\n\n\n\n<p>The <code>yield<\/code> keyword produces a series of values and returns when requested by the caller.<\/p>\n\n\n\n<p>The <code>yield<\/code> keyword <strong>temporarily freezes the execution of the function<\/strong> and <strong>returns the value to the caller<\/strong>. As it freezes the execution, <strong>the state of the function is preserved and allows the function to resume from where it was left off<\/strong>.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1400\" height=\"1000\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2024\/03\/image.png\" alt=\"Working of yield when a function encounters it\" class=\"wp-image-1660\" srcset=\"https:\/\/geekpython.in\/wp-content\/uploads\/2024\/03\/image.png 1400w, https:\/\/geekpython.in\/wp-content\/uploads\/2024\/03\/image-300x214.png 300w, https:\/\/geekpython.in\/wp-content\/uploads\/2024\/03\/image-1024x731.png 1024w, https:\/\/geekpython.in\/wp-content\/uploads\/2024\/03\/image-768x549.png 768w\" sizes=\"auto, (max-width: 1400px) 100vw, 1400px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">yield Keyword in a Function<\/h2>\n\n\n\n<p>You can define a normal function as usual with the <code>def<\/code> keyword, but instead of the <code>return<\/code> keyword, use the <code>yield<\/code> keyword in the function body.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># A function with yield kw - a generator function\ndef random_func():\n    # Yield values\n    yield \"random1\"\n    yield \"random2\"\n    yield \"random3\"\n\n# Instance of the function\nobj = random_func()<\/pre><\/div>\n\n\n\n<p>The above code defines a function named <code>random_func()<\/code>, which is essentially a generator function due to the <code>yield<\/code> keyword in the function body.<\/p>\n\n\n\n<p>Now, this is a simple generator function that yields three values and returns them when requested. The function is initialized (<code>random_func()<\/code>) and saved in the <code>obj<\/code> variable.<\/p>\n\n\n\n<p>When you print the <code>obj<\/code> variable, you will receive the generator object.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">...\nprint(obj)\n--------------------\n&lt;generator object random_func at 0x0000026E95924880&gt;<\/pre><\/div>\n\n\n\n<p><strong>So, how do you access the yielded values one at a time?<\/strong> The values can be accessed by using the caller&#8217;s <code>__next__()<\/code> method, as shown below.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Instance of the function\nobj = random_func()\n# Calling __next__() method on the instance\nprint(obj.__next__())   # or print(next(obj))\nprint(obj.__next__())   # or print(next(obj))\nprint(obj.__next__())   # or print(next(obj))\n--------------------\nrandom1\nrandom2\nrandom3<\/pre><\/div>\n\n\n\n<p>The <code>__next__()<\/code> method is called three times to retrieve all three values returned by the function. You can also iterate over the <code>obj<\/code> variable with the <code>for<\/code> loop to get the values, which is more efficient than repeatedly calling the <code>__next__()<\/code> method when you need to consume all of the yielded values.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Instance of the function\nobj = random_func()\n# Iterating through the instance\nfor value in obj:\n    print(value)\n--------------------\nrandom1\nrandom2\nrandom3<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">How yield Works in a Function?<\/h2>\n\n\n\n<p><strong>How does the execution flow in the function containing the <\/strong><code>yield<\/code><strong> statement?<\/strong> Let&#8217;s keep it very simple and understand with an example.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">import logging\n\n# Configuring logging\nlogging.basicConfig(level=logging.INFO)\n\n# Simple generator function\ndef generate_val():\n    logging.info(\"Start\")\n    value = 0\n    logging.info(\"Before entering the loop\")\n    while True:\n        logging.info(\"Before yield statement\")\n        yield value\n        logging.info(\"After yield statement\")\n        value += 1\n\ngen = generate_val()\nprint(next(gen))\nprint(next(gen))\nprint(next(gen))<\/pre><\/div>\n\n\n\n<p>The above code defines a basic generator function <code>generate_val()<\/code> that generates an infinite sequence of values starting from 0. It uses the <code>yield<\/code> statement to yield each value and increments it by 1 in each iteration of the loop.<\/p>\n\n\n\n<p>The <code><a href=\"https:\/\/docs.python.org\/3\/howto\/logging.html#logging-basic-tutorial\" target=\"_blank\" rel=\"noopener\">logging<\/a><\/code> module is used to log the information. It logs various messages at different points in the generator function&#8217;s execution to provide information about its flow.<\/p>\n\n\n\n<p>When you run the code, the following output will be generated.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex decode:true \">0\n1\n2\nINFO:root:Start\nINFO:root:Before entering the loop\nINFO:root:Before yield statement\nINFO:root:After yield statement\nINFO:root:Before yield statement\nINFO:root:After yield statement\nINFO:root:Before yield statement<\/pre><\/div>\n\n\n\n<p>Notice that when the program enters the loop and encounters the <code>yield<\/code> statement, it returns the value for the first iteration (<code>next(gen)<\/code>), suspends the execution flow immediately, and then resumes from where it left off for the next iteration.<\/p>\n\n\n\n<p>This will happen with each iteration, and the program will never exit the function until stopped manually.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">StopIteration Exception<\/h2>\n\n\n\n<p>In the above section, the program runs infinitely and never exhausts. What happens when the generator function has nothing else to evaluate?<\/p>\n\n\n\n<p>Let&#8217;s understand with a basic example.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Function to yield only even number\ndef only_even(n):\n    try:\n        num = 0\n        while num &lt;= n:\n            if num % 2 == 0:\n                yield num\n            num += 1\n    except Exception as e:\n        print(f\"Error - {str(e)}.\")<\/pre><\/div>\n\n\n\n<p>The code above defines the <code>only_even()<\/code> function, which accepts an argument <code>n<\/code> and returns even numbers up to <code>n<\/code>, including <code>n<\/code>, if it is an even number.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Function to yield only even number\n...\n\neven = only_even(3)<\/pre><\/div>\n\n\n\n<p>The function (<code>only_even()<\/code>) is instantiated with the argument <code>3<\/code> and stored in the <code>even<\/code> variable.<\/p>\n\n\n\n<p>The function can now generate even numbers up to 3 (0 and 2), which means you can use the <code>next()<\/code> method on &#8220;<code>even<\/code>&#8221; twice. What happens if you call the <code>next()<\/code> method more than twice?<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Function to yield only even number\n...\n\neven = only_even(3)\nprint(next(even))\nprint(next(even))\nprint(next(even))    # Raises an error<\/pre><\/div>\n\n\n\n<p>For the first two iterations, the function returns an even number. In the third iteration, the loop is executed until <code>num &lt;= n<\/code> becomes false. If the generator produces no more items, the <code>StopIteration<\/code> error is returned.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex mark:7 decode:true \">0\n2\nTraceback (most recent call last):\n  ...\n    print(next(even))\n          ^^^^^^^^^^\nStopIteration<\/pre><\/div>\n\n\n\n<p>To avoid the <code>StopIteration<\/code> error, you can use a <code>for<\/code> loop. A <code>for<\/code> loop automatically catches <code>StopIteration<\/code> exceptions and terminates gracefully when the iterator is exhausted.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Function to yield only even number\n...\n\neven = only_even(9)\nfor num in even:\n    print(num)\n\n--------------------\n0\n2<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">When to Use yield?<\/h2>\n\n\n\n<p>You can use a <code>yield<\/code> statement in a function when you want to generate a sequence of values lazily (generate values when requested) rather than computing and storing them in memory until you print them.<\/p>\n\n\n\n<p>Let&#8217;s say you want to create a function that returns all the even numbers between 0 and 100000000.<\/p>\n\n\n\n<p>Using the <code>return<\/code> keyword in the function computes all of the values and stores them in memory, when you print them, the program dumps them all at once.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">def only_even(n):\n    number = []\n    for num in range(n):\n        if num % 2 == 0:\n            number.append(num)\n    return number\n\neven = only_even(100000000)\nfor number in even:\n    print(number)<\/pre><\/div>\n\n\n\n<p>If you include a <code>yield<\/code> statement in the function, you can generate values as they are needed.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">def only_even(n):\n    num = 0\n    while num &lt;= n:\n        if num % 2 == 0:\n            yield num\n        num += 1\n\neven = only_even(100000000)\nfor val in even:\n    print(val)<\/pre><\/div>\n\n\n\n<p>So, what is the main difference between the two programs? If you run the first program (function with <code>return<\/code> keyword), the function will compute the values and store them in memory until the program reaches the <code>print<\/code> statement, at which point it will print them, whereas the second program (function with <code>yield<\/code> keyword) generates values on-the-fly as they are requested, rather than computing and storing all of the values in memory at once.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>The <code>yield<\/code> keyword in a function body means that the function is a generator function and the <code>yield<\/code> produces a sequence of values and returns when the value is requested by the caller.<\/p>\n\n\n\n<p>The <code>yield<\/code> keyword remembers the state of the function and allows the function to resume from where it was left followed by the first iteration.<\/p>\n\n\n\n<p>Let&#8217;s recall what you&#8217;ve learned:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>What is <code>yield<\/code> in Python?<\/li>\n\n\n\n<li>How the execution flows in a function containing the <code>yield<\/code><\/li>\n\n\n\n<li>What happens when the generator has no more items to evaluate<\/li>\n\n\n\n<li>When to use generator functions (function with <code>yield<\/code> keyword)<\/li>\n<\/ul>\n\n\n\n<p>Reference: <a href=\"https:\/\/peps.python.org\/pep-0255\/#specification-yield\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/peps.python.org\/pep-0255\/#specification-yield<\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/python-generators-with-yield-statement\">What are generator functions and how do they work in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/pickle-module-in-python\">Serialize and deserialize Python objects using the pickle module<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/build-websocket-server-and-client-using-python\">Create a WebSocket server and client in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/threading-module-to-create-threads-in-python\">Create multi-threaded Python programs using a threading module<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/create-and-integrate-mysql-database-with-flask-app\">Create and integrate MySQL database with Flask app using Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/render-images-from-flask\">Upload and display images on the frontend using Flask<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>To return a value from a Python function, you must have used the return keyword. When the program encounters the return keyword, it exits the function and returns the value to the caller before proceeding to execute additional code. However, the case is entirely different with the yield keyword. It does control the flow of [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1659,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[2],"tags":[31,77],"class_list":["post-1657","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python3","tag-yield","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1657","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1657"}],"version-history":[{"count":6,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1657\/revisions"}],"predecessor-version":[{"id":1699,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1657\/revisions\/1699"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1659"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1657"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1657"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1657"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}