Zone Of Makos

Menu icon

Iterators in Python

An iterator is an object that allows you to traverse a collection of data, one element at a time. In Python, an iterator is any object that implements the iterator protocol, which consists of two methods: __iter__() and __next__(). The __iter__() method returns the iterator object itself, while the __next__() method returns the next element in the sequence. In this lesson, we'll explore how to use iterators in Python and how they can help you write more efficient and memory-friendly code.

Creating Iterators in Python

In Python, you can create an iterator by defining a class that implements the iterator protocol. The __iter__() method should return the iterator object itself, while the __next__() method should return the next element in the sequence. When there are no more elements in the sequence, the __next__() method should raise the StopIteration exception.


class MyIterator:
    def __init__(self, my_list):
        self.my_list = my_list
        self.index = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.index >= len(self.my_list):
            raise StopIteration
        result = self.my_list[self.index]
        self.index += 1
        return result

my_list = [1, 2, 3, 4, 5]
my_iterator = MyIterator(my_list)

for item in my_iterator:
    print(item)

Built-in Iterators in Python

Python provides several built-in iterators that you can use to traverse common data structures, such as lists, tuples, and dictionaries. Some examples of built-in iterators include the range() function, which generates a sequence of numbers, and the enumerate() function, which returns both the index and value of each element in a sequence.


my_list = [1, 2, 3, 4, 5]

# Using a for loop
for item in my_list:
    print(item)

# Using an iterator
my_iterator = iter(my_list)
while True:
    try:
        item = next(my_iterator)
        print(item)
    except StopIteration:
        break

# Using the built-in range() function
for i in range(5):
    print(i)

# Using the built-in enumerate() function
my_list = ['apple', 'banana', 'cherry']
for i, item in enumerate(my_list):
    print(i, item)

Conclusion

Iterators are a powerful feature of Python that allow you to traverse a collection of data, one element at a time. In Python, an iterator is any object that implements the iterator protocol, which consists of the __iter__() and __next__() methods. You can create your own iterators by defining a class that implements the iterator protocol, or you can use the many built-in iterators provided by Python. Iterators can help you write more efficient and memory-friendly code, and they are an essential part of many advanced programming concepts in Python.