Python

 

 

🔹 Introduction

Python generators provide a powerful way to work with iterators and lazy evaluation. They allow you to create functions that yield values one at a time, instead of returning everything at once.
This can save memory and improve performance, especially when working with large datasets.

🎯 Objective

In this guide, you’ll learn how to:

  • Create a generator using the yield keyword
  • Use a generator in a for loop
  • Understand how generators help with memory efficiency

💻 Example Code


def number_generator(n):
    """A simple generator that yields numbers from 1 to n."""
    for i in range(1, n + 1):
        yield i

# Using the generator
print("Generated numbers:")
for number in number_generator(5):
    print(number)
    

📘 Explanation

Let’s break down the program:

  • number_generator(n): A generator function that uses yield to produce numbers one at a time from 1 to n.
  • yield: Pauses the function and returns a value. On next call, continues from where it left off.
  • for number in number_generator(5): Iterates through each yielded value until the generator is exhausted.

🚀 How to Run the Program

You can run this script in any Python 3 environment:

  • Save the code in a file named generator_example.py
  • Open a terminal or command prompt
  • Run the command: python generator_example.py
  • You should see the numbers 1 through 5 printed, one per line

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)