π Day 99/150 – Generator Example in Python
A generator is a special type of function that produces values one at a time instead of returning all values at once. It uses the yield keyword instead of return, making it memory-efficient, especially when working with large datasets.
In this post, we'll explore four common examples of generators in Python.
Method 1 – Basic Generator
Create a simple generator that yields numbers one by one.
def numbers(): yield 1 yield 2 yield 3 gen = numbers() print(next(gen)) print(next(gen)) print(next(gen))
Output
1 2 3
Explanation
- yield returns a value and pauses the function.
- next() resumes the generator from where it stopped.
- Each call to next() produces the next value.
Method 2 – Generator with a Loop
Generate numbers from 1 to n.
1 2 3 4 5def count(n): for i in range(1, n + 1): yield i for num in count(5): print(num)
Output
Explanation
- The for loop generates numbers one by one.
- yield returns each number individually.
- The generator stops automatically after the last value.
Method 3 – Generator Expression
Python also provides generator expressions, which are similar to list comprehensions.
squares = (x ** 2 for x in range(1, 6)) for square in squares: print(square)
Output
1 4 9 16 25Explanation
- (x ** 2 for x in range(1, 6)) creates a generator expression.
- Unlike a list comprehension, it doesn't store all values in memory.
- Values are generated only when needed.
Method 4 – Taking User Input
Generate numbers from 1 to the number entered by the user.
5def generate_numbers(n): for i in range(1, n + 1): yield i num = int(input("Enter a number: ")) for value in generate_numbers(num): print(value)
Sample Input
Output
1 2 3 4 5Explanation
- The user enters a number.
- The generator produces numbers from 1 to that number.
- Each value is generated only when the loop requests it.
Comparison of Methods
| Method | Best For |
|---|---|
| Basic Generator | Understanding yield |
| Generator with Loop | Generating sequences |
| Generator Expression | Memory-efficient computations |
| User Input | Interactive programs |
π₯ Key Takeaways
- A generator is a function that uses the yield keyword.
- yield returns one value at a time and pauses the function.
- Generators are more memory-efficient than lists because they don't store all values at once.
- Use next() to retrieve values manually from a generator.
- Generator expressions provide a concise way to create generators.
- Generators are useful when working with large datasets or continuous data streams.


0 Comments:
Post a Comment