{"id":20781,"date":"2020-08-04T23:56:28","date_gmt":"2020-08-05T06:56:28","guid":{"rendered":"https:\/\/careerkarma.com\/blog\/?p=20781"},"modified":"2023-12-01T03:57:19","modified_gmt":"2023-12-01T11:57:19","slug":"python-yield","status":"publish","type":"post","link":"https:\/\/careerkarma.com\/blog\/python-yield\/","title":{"rendered":"The Python Yield Keyword: A Guide"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">How to Use the Python Yield Keyword<\/h2>\n\n\n\n<p>Generators aren\u2019t the most intuitive concept in <a href=\"https:\/\/careerkarma.com\/blog\/what-python-is-used-for\/\">Python<\/a>. To make matters worse, they use a special keyword called \u201cyield,\u201d even though generators are themselves functions. What is the yield keyword? How does it compare to a return statement?<br><\/p>\n\n\n\n<p>Those are good questions. In this guide, we talk about what the yield statement is and how you can use it in your code. We walk through an example of the yield keyword in action. Let\u2019s get started!<br><\/p>\n\n\n\n<p>We recommend reading our articles on <a href=\"https:\/\/careerkarma.com\/blog\/python-iterator\/\">Python iterators<\/a> and <a href=\"https:\/\/careerkarma.com\/blog\/python-generator\/\">generators<\/a> before continuing. This gives you some useful context that you can use to further your understanding of the yield keyword.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Back to Basics: Iterators and Generators<\/h2>\n\n\n\n<p>Lists are described as iterable objects. This is because you can view their contents using a \u201cfor\u201d loop. Every time the loop executes, an item in the list is accessed by Python. Dictionaries, tuples, and strings are also iterable objects.<br><\/p>\n\n\n\n<p>A function that accesses an item from an iterable object is called an <strong>iterator<\/strong>. Let\u2019s create a list and iterate over it using a <a href=\"https:\/\/careerkarma.com\/blog\/python-for-loop\/\">for loop<\/a>:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>peppers = [&quot;Scotch Bonnet&quot;, &quot;Piri Piri&quot;, &quot;Cayenne&quot;]\n\nfor p in peppers:\n\tprint(p)\nfor p in peppers:\n\tprint(p)<\/pre><\/div>\n\n\n\n<p>This code prints out all of the peppers in the \u201cpeppers\u201d list to the console:<br><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>Scotch Bonnet\nPiri Piri\nCayenne\nScotch Bonnet\nPiri Piri\nCayenne<\/pre><\/div>\n\n\n\n<p>We use our iterator as many times as we want. In the last example, we iterated over the \u201cpeppers\u201d object twice.<br><\/p>\n\n\n\n<p>Python generators are like an iterator used to repeat an object. There is one big difference: You can only iterate over a generator once. Whereas we can iterate over \u201cpeppers\u201d as many times as we want, a generator is only accessed once.<br><\/p>\n\n\n\n<p>Let\u2019s define a generator for our list of peppers:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>def print_peppers(peppers):\n\tfor p in peppers:\n\t\tyield p\n\npeppers = [&quot;Scotch Bonnet&quot;, &quot;Piri Piri&quot;, &quot;Cayenne&quot;]\npepper_generator = print_peppers(peppers)\n\nfor p in pepper_generator:\n\tprint(p)<\/pre><\/div>\n\n\n\n<p>We define a function called <code>print_peppers()<\/code>. This is our generator <a href=\"https:\/\/careerkarma.com\/blog\/python-functions\/\">function<\/a>. It accepts one argument: a list of peppers that we want to print to the console.<br><\/p>\n\n\n\n<p>In our main program, we call the <code>print_peppers()<\/code> function and assign it to the variable pepper_generator. Next, we iterate over the generator using a \u201cfor\u201d loop. Our for loop calls the generator object and iterates over it.<br><\/p>\n\n\n\n<p>Let\u2019s run our code:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>Scotch Bonnet\nPiri Piri\nCayenne<\/pre><\/div>\n\n\n\n<p>The output is the same as our first example. The difference is we can only iterate over our list once. Let\u2019s try to iterate over our generator again:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>...\nfor p in pepper_generator:\n\tprint(p)\nfor p in pepper_generator:\n\tprint(p)<\/pre><\/div>\n\n\n\n<p>Our code returns:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>Scotch Bonnet\nPiri Piri\nCayenne<\/pre><\/div>\n\n\n\n<p>We\u2019ve iterated over our generator once. We cannot do it again. That\u2019s why our second for loop does not return any values.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Python Yield Keyword<\/h2>\n\n\n\n<p>Notice the word \u201cyield\u201d in the last example. Here\u2019s a reminder:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>def print_peppers(peppers):\n\tfor p in peppers:\n\t\tyield p<\/pre><\/div>\n\n\n\n<p>The \u201cyield\u201d keyword appears inside our function. It returns a value in a generator function. It\u2019s similar to the <a href=\"https:\/\/careerkarma.com\/blog\/python-return\/\">\u201creturn\u201d keyword<\/a>.<br><\/p>\n\n\n\n<p>Use yield when you want to create a generator over which you can iterate. In our last example, we use yield to create a generator for our list of peppers.<br><\/p>\n\n\n\n<p>Any function that contains yield will return a generator. We see this by checking the type of the pepper_generator variable using the <code>type()<\/code> method:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>&lt;class 'generator'&gt;<\/pre><\/div>\n\n\n\n<p>This tells us that pepper_generator, which is assigned the print_peppers function, is a generator.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>The yield keyword returns a value inside a generator. A generator is a special type of iterator whose values can only be iterated over once. The yield keyword is similar to a return statement except return statements cannot be used in generators.<br><\/p>\n\n\n\n<p>Now you\u2019re ready to use the yield keyword like a Pythonista!<\/p>\n","protected":false},"excerpt":{"rendered":"How to Use the Python Yield Keyword Generators aren\u2019t the most intuitive concept in Python. To make matters worse, they use a special keyword called \u201cyield,\u201d even though generators are themselves functions. What is the yield keyword? How does it compare to a return statement? Those are good questions. In this guide, we talk about&hellip;","protected":false},"author":240,"featured_media":20782,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[16578],"tags":[],"class_list":{"0":"post-20781","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python"},"acf":{"post_sub_title":"","sprint_id":"","query_class":"Python","school_sft":"","parent_sft":"","school_privacy_policy":"","has_review":null,"is_sponser_post":"","is_guest_post":""},"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.0 (Yoast SEO v27.0) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>The Python Yield Keyword: A Guide | Career Karma<\/title>\n<meta name=\"description\" content=\"The yield keyword returns values in a generator function. On Career Karma, learn how to use the Python yield keyword.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/careerkarma.com\/blog\/python-yield\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"The Python Yield Keyword: A Guide\" \/>\n<meta property=\"og:description\" content=\"The yield keyword returns values in a generator function. On Career Karma, learn how to use the Python yield keyword.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/careerkarma.com\/blog\/python-yield\/\" \/>\n<meta property=\"og:site_name\" content=\"Career Karma\" \/>\n<meta property=\"article:publisher\" content=\"http:\/\/facebook.com\/careerkarmaapp\" \/>\n<meta property=\"article:published_time\" content=\"2020-08-05T06:56:28+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-12-01T11:57:19+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1020\" \/>\n\t<meta property=\"og:image:height\" content=\"680\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"James Gallagher\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@career_karma\" \/>\n<meta name=\"twitter:site\" content=\"@career_karma\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"James Gallagher\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/\"},\"author\":{\"name\":\"James Gallagher\",\"@id\":\"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94\"},\"headline\":\"The Python Yield Keyword: A Guide\",\"datePublished\":\"2020-08-05T06:56:28+00:00\",\"dateModified\":\"2023-12-01T11:57:19+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/\"},\"wordCount\":569,\"commentCount\":0,\"image\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg\",\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/careerkarma.com\/blog\/python-yield\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/\",\"url\":\"https:\/\/careerkarma.com\/blog\/python-yield\/\",\"name\":\"The Python Yield Keyword: A Guide | Career Karma\",\"isPartOf\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg\",\"datePublished\":\"2020-08-05T06:56:28+00:00\",\"dateModified\":\"2023-12-01T11:57:19+00:00\",\"author\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94\"},\"description\":\"The yield keyword returns values in a generator function. On Career Karma, learn how to use the Python yield keyword.\",\"breadcrumb\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/careerkarma.com\/blog\/python-yield\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/#primaryimage\",\"url\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg\",\"contentUrl\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg\",\"width\":1020,\"height\":680},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/careerkarma.com\/blog\/python-yield\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Blog\",\"item\":\"https:\/\/careerkarma.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python\",\"item\":\"https:\/\/careerkarma.com\/blog\/python\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"The Python Yield Keyword: A Guide\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/careerkarma.com\/blog\/#website\",\"url\":\"https:\/\/careerkarma.com\/blog\/\",\"name\":\"Career Karma\",\"description\":\"Latest Coding Bootcamp News &amp; Career Hacks from Industry Insiders\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/careerkarma.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94\",\"name\":\"James Gallagher\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/01\/james-gallagher-150x150.jpg\",\"contentUrl\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/01\/james-gallagher-150x150.jpg\",\"caption\":\"James Gallagher\"},\"description\":\"James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tutorials, and he frequently contributes to publications like Codecademy, Treehouse, Repl.it, Afrotech, and others.\",\"url\":\"https:\/\/careerkarma.com\/blog\/author\/jamesgallagher\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"The Python Yield Keyword: A Guide | Career Karma","description":"The yield keyword returns values in a generator function. On Career Karma, learn how to use the Python yield keyword.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/careerkarma.com\/blog\/python-yield\/","og_locale":"en_US","og_type":"article","og_title":"The Python Yield Keyword: A Guide","og_description":"The yield keyword returns values in a generator function. On Career Karma, learn how to use the Python yield keyword.","og_url":"https:\/\/careerkarma.com\/blog\/python-yield\/","og_site_name":"Career Karma","article_publisher":"http:\/\/facebook.com\/careerkarmaapp","article_published_time":"2020-08-05T06:56:28+00:00","article_modified_time":"2023-12-01T11:57:19+00:00","og_image":[{"width":1020,"height":680,"url":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg","type":"image\/jpeg"}],"author":"James Gallagher","twitter_card":"summary_large_image","twitter_creator":"@career_karma","twitter_site":"@career_karma","twitter_misc":{"Written by":"James Gallagher","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/careerkarma.com\/blog\/python-yield\/#article","isPartOf":{"@id":"https:\/\/careerkarma.com\/blog\/python-yield\/"},"author":{"name":"James Gallagher","@id":"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94"},"headline":"The Python Yield Keyword: A Guide","datePublished":"2020-08-05T06:56:28+00:00","dateModified":"2023-12-01T11:57:19+00:00","mainEntityOfPage":{"@id":"https:\/\/careerkarma.com\/blog\/python-yield\/"},"wordCount":569,"commentCount":0,"image":{"@id":"https:\/\/careerkarma.com\/blog\/python-yield\/#primaryimage"},"thumbnailUrl":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg","articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/careerkarma.com\/blog\/python-yield\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/careerkarma.com\/blog\/python-yield\/","url":"https:\/\/careerkarma.com\/blog\/python-yield\/","name":"The Python Yield Keyword: A Guide | Career Karma","isPartOf":{"@id":"https:\/\/careerkarma.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/careerkarma.com\/blog\/python-yield\/#primaryimage"},"image":{"@id":"https:\/\/careerkarma.com\/blog\/python-yield\/#primaryimage"},"thumbnailUrl":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg","datePublished":"2020-08-05T06:56:28+00:00","dateModified":"2023-12-01T11:57:19+00:00","author":{"@id":"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94"},"description":"The yield keyword returns values in a generator function. On Career Karma, learn how to use the Python yield keyword.","breadcrumb":{"@id":"https:\/\/careerkarma.com\/blog\/python-yield\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/careerkarma.com\/blog\/python-yield\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/careerkarma.com\/blog\/python-yield\/#primaryimage","url":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg","contentUrl":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/08\/christin-hume-hBuwVLcYTnA-unsplash.jpg","width":1020,"height":680},{"@type":"BreadcrumbList","@id":"https:\/\/careerkarma.com\/blog\/python-yield\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog","item":"https:\/\/careerkarma.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Python","item":"https:\/\/careerkarma.com\/blog\/python\/"},{"@type":"ListItem","position":3,"name":"The Python Yield Keyword: A Guide"}]},{"@type":"WebSite","@id":"https:\/\/careerkarma.com\/blog\/#website","url":"https:\/\/careerkarma.com\/blog\/","name":"Career Karma","description":"Latest Coding Bootcamp News &amp; Career Hacks from Industry Insiders","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/careerkarma.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94","name":"James Gallagher","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/01\/james-gallagher-150x150.jpg","contentUrl":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/01\/james-gallagher-150x150.jpg","caption":"James Gallagher"},"description":"James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tutorials, and he frequently contributes to publications like Codecademy, Treehouse, Repl.it, Afrotech, and others.","url":"https:\/\/careerkarma.com\/blog\/author\/jamesgallagher\/"}]}},"_links":{"self":[{"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/posts\/20781","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/users\/240"}],"replies":[{"embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/comments?post=20781"}],"version-history":[{"count":0,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/posts\/20781\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/media\/20782"}],"wp:attachment":[{"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/media?parent=20781"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/categories?post=20781"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/tags?post=20781"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}