Python Generators & Iterators
1. What are Iterators and Generators?
Both iterators and generators are used to go through values one by one.
In simple words:
👉 They give one value at a time
👉 They save memory
👉 They are useful for large data
2. What is an Iterator?
An iterator is an object that:
-
Remembers its position
-
Gives next value when asked
Python uses:
-
012345678iter() → create iteratornext() → get next value
3. Simple Iterator Example (List)
Example
Output:
4. Iterator Stops Automatically
When values finish, Python gives StopIteration error.
Example
5. Iterator with for Loop (Easy Way)
Python handles iterator automatically in for loop.
Example
6. Create Your Own Iterator (Basic)
To create your own iterator, you need:
-
012345678__iter__()__next__()
Example
7. What is a Generator?
A generator is a simpler way to create an iterator.
In simple words:
👉 Generator is a function
👉 Uses yield instead of return
👉 Automatically remembers state
8. Simple Generator Example
Example
9. Generator vs Normal Function
Normal Function
👉 Returns only once.
Generator Function
👉 Returns many values, one by one.
10. Generator with Loop
Example
11. Generator Expression (Short Form)
Like list comprehension, but uses ().
Example
12. Generator vs Iterator (Simple Table)
| Iterator | Generator |
|---|---|
| Uses class | Uses function |
| More code | Less code |
| Manual control | Automatic |
| Harder | Easier |
👉 Beginners prefer generators.
13. Why Use Generators & Iterators?
✔ Save memory
✔ Faster for big data
✔ Clean code
✔ Used in real applications
14. Common Beginner Mistakes
❌ Using return instead of yield
❌ Not a generator.
❌ Reusing Generator
👉 Generator works only once.
15. Simple Practice Examples
Example 1: Even Numbers Generator
Example 2: Countdown Generator
Example 3: Iterator from String
16. Summary (Generators & Iterators)
✔ Both give values one by one
✔ Iterators use iter() and next()
✔ Generators use yield
✔ Generators are easier
✔ Very useful for large data
📘 Perfect for Beginner & Intermediate eBook
This chapter is ideal for:
-
Python learners
-
Interview preparation
-
Memory-efficient coding
-
Real-world projects
If you want next, I can write:
-
Advanced Generators
-
Iterator vs Generator (Deep)
-
Real Python Projects
-
Python Performance Tips
Just tell me 😊
