Python Iterators

Iterators are objects in Python that allow you to iterate over a sequence of elements, such as a list or a tuple. They provide a way to access the elements of a sequence one by one without having to know the internal structure of the sequence.

Iterating with a For Loop

The most common way to use an iterator in Python is with a for loop. For example, iterating over a list of numbers:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

Creating an Iterator

You can create your own iterator in Python by implementing the __iter__() and __next__() methods. The __iter__() method should return the iterator object itself, and the __next__() method should return the next element in the sequence or raise a StopIteration exception if there are no more elements. For example, creating an iterator for a range of numbers:

class MyRange:
    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.end:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

my_range = MyRange(1, 5)
for num in my_range:
    print(num)

Conclusion

Iterators are a fundamental concept in Python that allow you to iterate over sequences of elements. By understanding how to use iterators and create your own iterators, you can work more effectively with iterable objects in Python.



[ Footer Placeholder]