{"id":2158,"date":"2026-05-04T06:11:05","date_gmt":"2026-05-04T06:11:05","guid":{"rendered":"https:\/\/www.examtopics.info\/blog\/?p=2158"},"modified":"2026-11-04T19:57:09","modified_gmt":"2026-11-04T19:57:09","slug":"learn-python-generators-and-yield-improve-performance-with-simple-examples","status":"publish","type":"post","link":"https:\/\/www.examtopics.info\/blog\/learn-python-generators-and-yield-improve-performance-with-simple-examples\/","title":{"rendered":"Learn Python Generators and Yield: Improve Performance with Simple Examples"},"content":{"rendered":"<p>A Python generator is an iterator that computes values when a caller asks for them. The <code>yield<\/code> statement suspends a function and preserves its local execution state. That can reduce peak memory compared with eagerly building a list, but it does not automatically make computation faster or remove the need to close files and release resources. These examples show when laziness is useful and how to avoid common mistakes.<\/p>\n<h2>Start with one generator and a visible state change<\/h2>\n<pre><code class=\"language-python\">def countdown(start):\n    while start &gt; 0:\n        yield start\n        start -= 1\n\nvalues = countdown(3)\nprint(next(values))  # 3\nprint(next(values))  # 2\nprint(list(values))  # [1]<\/code><\/pre>\n<p>Calling <code>countdown(3)<\/code> returns a generator object; the body has not executed yet. Each <code>next()<\/code> resumes execution from the previous <code>yield<\/code>. Once exhausted, the generator raises <code>StopIteration<\/code>, which a <code>for<\/code> loop handles automatically. Iterating over the same exhausted generator again does not restart it; create a new generator instead.<\/p>\n<h2>Compare an eager list with an on-demand stream<\/h2>\n<pre><code class=\"language-python\">def squared_values(limit):\n    for number in range(limit):\n        yield number * number\n\nprint(sum(squared_values(5)))  # 30\nprint([x * x for x in range(5)])  # [0, 1, 4, 9, 16]<\/code><\/pre>\n<p>The generator version can feed values directly to <code>sum<\/code> without storing a separate list. The list comprehension is better when you need to index, inspect or traverse the values repeatedly. A generator expression, <code>(x*x for x in range(5))<\/code>, offers compact laziness without defining a named function. Choose based on the consumer\u2019s requirements, not a blanket rule that generators are always superior.<\/p>\n<h2>Stream a file safely and close it predictably<\/h2>\n<pre><code class=\"language-python\">def nonempty_lines(path):\n    with open(path, encoding=&quot;utf-8&quot;) as stream:\n        for raw_line in stream:\n            text = raw_line.strip()\n            if text:\n                yield text\n\nfor line in nonempty_lines(&quot;notes.txt&quot;):\n    print(line)<\/code><\/pre>\n<p>The file is opened when the generator first starts advancing. The <code>with<\/code> block ensures that normal exhaustion or generator closure releases the file. If a caller abandons a partially consumed generator, explicitly close it or structure ownership around a context manager; do not assume that cleanup occurs at a predictable instant in every Python implementation. The code strips surrounding whitespace; if whitespace is meaningful, use a narrower newline-only trim.<\/p>\n<h2>Compose generators using yield from<\/h2>\n<pre><code class=\"language-python\">def groups():\n    yield from (&quot;alpha&quot;, &quot;beta&quot;)\n    yield from (&quot;gamma&quot;,)\n\nprint(list(groups()))  # [&#x27;alpha&#x27;, &#x27;beta&#x27;, &#x27;gamma&#x27;]<\/code><\/pre>\n<p><code>yield from<\/code> delegates iteration to another iterable. It is useful when a pipeline needs to combine sources without first creating a combined list. For large data processing, a sequence of small, readable generators can express parsing, filtering and transformation, but monitor whether an upstream resource remains open longer than expected.<\/p>\n<h2>Bound memory, work and errors<\/h2>\n<p>Lazy production is not the same as unlimited processing. A generator that feeds an unbounded source to <code>list()<\/code> or <code>sorted()<\/code> still accumulates all values. Use a deliberate consumer limit such as <code>itertools.islice<\/code> when exploring an infinite stream. If a generator raises an exception, the calling loop receives it; handle expected data errors at the appropriate boundary rather than quietly discarding corrupted records.<\/p>\n<pre><code class=\"language-python\">from itertools import islice\n\ndef natural_numbers():\n    number = 1\n    while True:\n        yield number\n        number += 1\n\nprint(list(islice(natural_numbers(), 4)))\n# [1, 2, 3, 4]<\/code><\/pre>\n<h2>Generators, asynchronous functions and performance<\/h2>\n<p>A regular generator uses <code>yield<\/code> to produce values during ordinary iteration. An <code>async def<\/code> function with <code>yield<\/code> creates an asynchronous generator, which is consumed with <code>async for<\/code>. The distinction matters: laziness alone does not schedule network requests concurrently. Async I\/O has separate await and cancellation rules explained in the existing <a href=\"https:\/\/www.examtopics.info\/blog\/python-asyncio-tutorial-create-high-performance-async-api-calls\/\">Python asyncio tutorial<\/a>.<\/p>\n<p>Measure real bottlenecks before optimizing. Generators may reduce memory pressure and improve clarity, but extra per-item Python overhead can make a short list faster. The official Python generator reference documents how iteration state is preserved and why generator functions automatically supply iterator methods.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A Python generator is an iterator that computes values when a caller asks for them. The yield statement suspends a function and preserves its local execution state. That can reduce peak memory compared with eagerly building a list, but it does not automatically make computation faster or remove the need to close files and release [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,14],"tags":[],"class_list":["post-2158","post","type-post","status-publish","format-standard","hentry","category-post","category-software-development"],"_links":{"self":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts\/2158","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/comments?post=2158"}],"version-history":[{"count":3,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts\/2158\/revisions"}],"predecessor-version":[{"id":6482,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts\/2158\/revisions\/6482"}],"wp:attachment":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/media?parent=2158"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/categories?post=2158"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/tags?post=2158"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}