Iterators Generators
Iterators Generators
In Python, **iterators** and **generators** are tools that enable e cient iteration over data.
While they are closely related, they have distinct characteristics and use cases.
---
### **Iterators**
An **iterator** is an object in Python that implements the **iterator protocol**. This protocol
consists of two methods:
1. `__iter__()`: Returns the iterator object itself. This allows the object to be used in `for` loops or
other iteration contexts.
2. `__next__()`: Returns the next item from the iterator. If there are no more items to return, it
raises a `StopIteration` exception.
```python
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self # The iterator object itself
def __next__(self):
if self.current > self.high:
raise StopIteration # End of iteration
else:
value = self.current
self.current += 1
return value
**Output**:
```
1
2
3
4
5
```
### **Generators**
```python
def countdown(start):
while start > 0:
yield start
start -= 1
**Output**:
```
5
4
3
2
1
```
---
```python
squares = (x * x for x in range(5))
for square in squares:
print(square)
```
**Output**:
```
0
1
4
9
16
```
---
---
```python
def in nite_sequence():
num = 0
while True:
yield num
num += 1
**Output**:
```
0
1
2
3
4
```
---
Generators can be used as building blocks for creating more complex iterators.
ffi
fi
fi
fi
fi
fi
fi
fi
ffi
fi
fi
```python
class Fibonacci:
def __init__(self, max_count):
self.max_count = max_count
def __iter__(self):
a, b, count = 0, 1, 0
while count < self.max_count:
yield a
a, b = b, a + b
count += 1
**Output**:
```
0
1
1
2
3
5
8
13
21
34
```
---
---