{"id":80,"date":"2025-10-21T04:36:18","date_gmt":"2025-10-21T04:36:18","guid":{"rendered":"https:\/\/codetypingpro.com\/?p=80"},"modified":"2025-12-17T07:48:35","modified_gmt":"2025-12-17T07:48:35","slug":"lesson-18-iterators-and-generators-in-python","status":"publish","type":"post","link":"https:\/\/codetypingpro.com\/?p=80","title":{"rendered":"Lesson 18: Iterators and Generators in Python"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">\ud83c\udfaf <strong>Lesson Objective<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To understand how <strong>iterators and generators<\/strong> work in Python for efficient data traversal and memory management.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\udde9 <strong>1. What Is an Iterator?<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">An <strong>iterator<\/strong> is an object that can be <strong>iterated (looped) over<\/strong>.<br>It implements two methods:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>__iter__()<\/code> \u2192 returns the iterator object itself<\/li>\n\n\n\n<li><code>__next__()<\/code> \u2192 returns the next value<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">\u2705 <strong>Example: Using Iterator on a List<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;1, 2, 3, 4]\nit = iter(numbers)\n\nprint(next(it))  # 1\nprint(next(it))  # 2\nprint(next(it))  # 3\nprint(next(it))  # 4\n# print(next(it))  # Raises StopIteration\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd04 <strong>2. Iterating Using a Loop<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;5, 10, 15]\nfor num in numbers:\n    print(num)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>5\n10\n15\n<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Python\u2019s <code>for<\/code> loop automatically uses iterators.<\/p>\n<\/blockquote>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\uddf0 <strong>3. Creating a Custom Iterator<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class MyRange:\n    def __init__(self, start, end):\n        self.current = start\n        self.end = end\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        if self.current &gt; self.end:\n            raise StopIteration\n        val = self.current\n        self.current += 1\n        return val\n\nnums = MyRange(1, 5)\nfor n in nums:\n    print(n)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>1\n2\n3\n4\n5\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\uddf1 <strong>4. What Is a Generator?<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A <strong>generator<\/strong> is a <strong>special function<\/strong> that <strong>yields values one by one<\/strong>, saving memory for large sequences.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u2705 <strong>Example: Generator Function<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def my_generator(n):\n    for i in range(1, n+1):\n        yield i\n\ngen = my_generator(5)\nfor val in gen:\n    print(val)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>1\n2\n3\n4\n5\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd04 <strong>5. Generator Expressions<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Similar to list comprehensions but use <strong>parentheses<\/strong> and generate values on the fly.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>squares = (x**2 for x in range(1, 6))\nfor val in squares:\n    print(val)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>1\n4\n9\n16\n25\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udee0\ufe0f <strong>6. Advantages of Generators<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Memory efficient \u2192 generate items <strong>one at a time<\/strong>.<\/li>\n\n\n\n<li>Can handle <strong>large datasets<\/strong>.<\/li>\n\n\n\n<li>Useful for pipelines and streaming data.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">\u2705 <strong>Example: Fibonacci Generator<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def fibonacci(n):\n    a, b = 0, 1\n    for _ in range(n):\n        yield a\n        a, b = b, a + b\n\nfor num in fibonacci(10):\n    print(num)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83c\udf0d <strong>7. Real-Life Example \u2013 Reading Large File<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>def read_file_line_by_line(filename):\n    with open(filename, \"r\") as file:\n        for line in file:\n            yield line.strip()\n\nfor line in read_file_line_by_line(\"example.txt\"):\n    print(line)\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Only <strong>one line is in memory at a time<\/strong>, efficient for large files.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udfaf Lesson Objective To understand how iterators and generators work in Python for efficient data traversal and memory management. \ud83e\udde9 1. What Is an Iterator? An iterator is an object that can be iterated (looped) over.It implements two methods: \u2705 Example: Using Iterator on a List \ud83d\udd04 2. Iterating Using a Loop Output: Python\u2019s for [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6,1],"tags":[],"class_list":["post-80","post","type-post","status-publish","format-standard","hentry","category-python-easy-course-outline","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/80","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=80"}],"version-history":[{"count":1,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/80\/revisions"}],"predecessor-version":[{"id":81,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/80\/revisions\/81"}],"wp:attachment":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=80"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=80"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=80"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}