β What is an Iterator?
An iterator is something you can loop through one item at a time.
π Think of it like:
A TV remote β every time you press the "Next" button (__next__()), it gives you the next channel (value).
π‘ In Python:
Any object with two methods:
__iter__()β returns the iterator object itself__next__()β returns the next item, or throws an error if no more items
πΉ Example:
numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3β What is a Generator?
A generator is a special function that behaves like an iterator.
But instead of returning all values at once, it yields them one at a time.
π Think of it like:
A water filter that gives one drop at a time when needed β instead of filling an entire bucket.
π§ Generator Example (Improved):
def countdown(n):
while n > 0:
yield n # Pause and give the current value
n -= 1 # Then continue
# Use the generator
for i in countdown(5):
print(i)5
4
3
2
1β Why Use a Generator?
Feature | Benefit |
|---|---|
π§ Memory efficient | Doesnβt store all values at once |
π’ Lazy evaluation | Only creates values when needed |
π§Ό Cleaner code | No need to write custom iterator classes |
π Great for big data | Like reading huge files line-by-line |
π Real-world Example β Reading Large File Line-by-Line
def read_file_lines(filepath):
with open(filepath, "r") as f:
for line in f:
yield line.strip() # yield each line without loading whole file
for line in read_file_lines("large_file.txt"):
print(line)π Summary Table:
Feature | Iterator | Generator |
|---|---|---|
How created | Using | Using |
Memory | Can be large if not careful | Very memory efficient |
Use Case | Loop over any object | Generate values on-the-fly |
Syntax | Needs class with | Just use |