🔁 Python Iterators (Made Simple)
Iterators are a way to go through all the elements in a collection (like a list or tuple), one item at a time. Python has built-in support for iterators, making it easy to loop through data.
If you've ever used a for loop in Python, you've already worked with iterators—even if you didn’t realize it!
✅ What Is an Iterator?
An iterator is an object that can be looped through (iterated over). It must follow two main rules:
- 
It must have a method called
__iter__()→ returns the iterator object itself. - 
It must have a method called
__next__()→ returns the next item from the sequence. 
📘 Example 1: Using an Iterator
my_list = [1, 2, 3]
# Get an iterator
my_iter = iter(my_list)
print(next(my_iter))  # Output: 1
print(next(my_iter))  # Output: 2
print(next(my_iter))  # Output: 3
🔍 Output:
1
2
3
If you call next() again after the list is finished, it will raise a StopIteration error.
🛠 Behind the Scenes of a For Loop
When we use a for loop like this:
for item in [1, 2, 3]:
    print(item)
Python automatically:
- 
Calls
iter()to get an iterator. - 
Calls
next()repeatedly untilStopIterationis raised. 
🧱 Building a Custom Iterator
Let’s create our own iterator to return numbers from 1 to 5.
📘 Example 2: Custom Iterator
class MyNumbers:
    def __iter__(self):
        self.num = 1
        return self
    def __next__(self):
        if self.num <= 5:
            x = self.num
            self.num += 1
            return x
        else:
            raise StopIteration
# Create object
nums = MyNumbers()
my_iter = iter(nums)
for number in my_iter:
    print(number)
🔍 Output:
1
2
3
4
5
💡 Important Notes
- 
iter()creates an iterator from an iterable (like a list or string). - 
next()returns the next value. - 
When there are no more items,
StopIterationis raised to end the loop. - 
You can create custom iterators by defining
__iter__()and__next__(). 
📘 Example 3: Iterating Over a String
Strings are also iterable!
my_str = "Hi"
my_iter = iter(my_str)
print(next(my_iter))  # Output: H
print(next(my_iter))  # Output: i
🔍 Output:
H
i
🎯 Conclusion
Iterators are a powerful tool in Python that let you go through items one at a time. Whether you’re working with lists, strings, or building custom sequences, understanding iterators helps us write clean and efficient code.
No comments:
Post a Comment