---
title: "Explain the concept of generators in Python with an example."  
description: "Explain the concept of generators in Python with an example."  
author: "Utpal Vishwas"  
published: 2023-06-26  
updated: 2023-06-27  
canonical: https://www.mindstick.com/forum/158873/explain-the-concept-of-generators-in-python-with-an-example  
category: "python"  
tags: ["python", "programs"]  
reading_time: 2 minutes  

---

# Explain the concept of generators in Python with an example.

[Explain the concept](https://www.mindstick.com/forum/159605/explain-the-concept-of-unique-key-violation-error) of [generators](https://www.mindstick.com/articles/310568/buying-guide-for-generators) in [Python](https://www.mindstick.com/articles/75378/simple-yet-useful-tips-when-using-python) with an example.

## Replies

### Reply by Aryan Kumar

Sure. A generator in Python is a special type of function that returns an iterator. Iterators are objects that can be iterated over, meaning that you can use them in a for loop. Generators are useful for producing large sequences of values, without having to store all of the values in memory at once.

Here is an example of a generator function:

Python

```plaintext
def fibonacci(n):
    a, b = 0, 1
    for i in range(n):
        yield a
        a, b = b, a + b

for i in fibonacci(10):
    print(i)
```

This function generates the Fibonacci sequence, which is a sequence of numbers where each number is the sum of the two previous numbers. The function starts by initializing two variables, `a` and `b`, to 0 and 1, respectively. Then, it enters a for loop that iterates 10 times. In each iteration of the loop, the function yields the value of `a` and then updates `a` and `b` to the Fibonacci numbers that follow `a`.

The `yield` keyword is used to produce a value from the generator. When the generator function is called, it does not execute the function body immediately. Instead, it returns a generator object that can be iterated over to produce the values.

When you iterate over the generator object, the function body will be executed one line at a time. The first time you iterate over the generator object, the first line of the function body will be executed, which will yield the value of `a`. The second time you iterate over the generator object, the second line of the function body will be executed, which will update `a` and `b` and then yield the value of `b`. This process will continue until the for loop finishes iterating, at which point the generator object will be exhausted.

Here is the output of the code:

Code snippet

```plaintext
0
1
1
2
3
5
8
13
21
34
```

As you can see, the code generates the first 10 Fibonacci numbers.


---

Original Source: https://www.mindstick.com/forum/158873/explain-the-concept-of-generators-in-python-with-an-example

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
