8 Python Generators
1. What is a Generator?
A generator is a special type of function that gives values one by one instead of all at once.
In simple words:
👉 A normal function returns everything at once
👉 A generator remembers its place
👉 It gives the next value only when asked
2. Why Use Generators?
Generators are useful because:
-
They save memory
-
They are fast for big data
-
They work one step at a time
3. Generator vs Normal Function
Normal Function
👉 Returns all values together.
Generator Function
👉 Returns values one by one.
4. Creating a Simple Generator
We use the keyword yield to create a generator.
Example
Output:
5. Generator with Loop
Example
6. How yield Works
-
yieldpauses the function -
Saves the value
-
Continues from same place next time
7. Generator Example: Even Numbers
Example
8. Generator Expression (Short Form)
|
0 1 2 3 4 5 6 |
Just like list comprehension, but uses ()instead of[]`. |
Example
9. Generator vs List (Memory Example)
List
👉 Uses more memory.
Generator
👉 Uses very little memory.
10. Generator Stops Automatically
When values are finished, generator stops.
Example
11. Common Beginner Mistakes
❌ Using return Instead of yield
❌ Generator stops at return.
❌ Calling Generator Again
👉 Generator runs only once.
12. Real-Life Example (Read Data Slowly)
Example
13. Simple Practice Examples
Example 1: Countdown Generator
Example 2: Squares Generator
Example 3: Odd Numbers
14. Summary (Python Generators)
✔ Use yield
✔ Returns values one by one
✔ Saves memory
✔ Faster for big data
✔ Generator runs only once
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
Iterator vs Generator
-
Modules
-
Exception Handling
-
File Handling
-
Mini Python Projects
Just tell me 😊
