2 Python Iterators
1. What is an Iterator?
An iterator is an object that lets us go through values one by one.
In simple words:
👉 An iterator remembers where it is
👉 It gives one value at a time
👉 It stops when values are finished
2. Real-Life Example (Easy)
Think of a TV remote 📺
-
Next button → next channel
-
One channel at a time
Iterator works the same way.
3. Iterable vs Iterator (Important)
Iterable
Something you can loop over
Examples:
-
list
-
tuple
-
string
-
set
Iterator
The object that actually gives values one by one
4. Simple Iterator Example (List)
Example
Output:
5. What are iter() and next()?
-
012345678iter() → creates an iteratornext() → gets next value
6. Iterator Stops Automatically
When items finish, Python raises StopIteration.
Example
7. Iterator with Loop (Easy Way)
We normally use for loop, Python handles iterator automatically.
Example
👉 Behind the scenes, Python uses iterator.
8. Iterator with String
Example
9. Creating Your Own Iterator (Basic)
To create your own iterator, you need:
-
012345678__iter__()__next__()
Example
10. Iterator vs Generator (Simple Difference)
| Iterator | Generator |
|---|---|
| Uses class | Uses function |
| More code | Less code |
| Manual control | Automatic |
👉 Generators are easier (we learned them before).
11. Common Beginner Mistakes
❌ Calling next() Too Many Times
❌ Error when values finish.
❌ Forgetting iter()
✔ Correct:
12. Simple Practice Examples
Example 1: Iterate Tuple
Example 2: Iterate String with Loop
Example 3: Manual Iterator
13. When Should You Use Iterators?
✔ When working with large data
✔ When memory saving is important
✔ When values come step by step
14. Summary (Python Iterators)
✔ Iterator gives values one by one
✔ Uses iter() and next()
✔ Stops with StopIteration
✔ for loop uses iterator internally
✔ Important concept in Python
📘 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 (full)
-
Comprehensions
-
Exception Handling
-
File Handling
-
Mini Python Projects
Just tell me 😊
