Iterator in python


In Python, an iterator is an object that allows you to traverse through all the elements of a collection (such as a list, tuple, or dictionary).

Iterators are a fundamental part of Python's iteration protocol, which consists of two main components:

  • Iterable: An object that can return an iterator. Examples include lists, tuples, and strings. Any object with an __iter__() method is iterable.
  • Iterator: An object that represents a stream of data. It implements two methods: __iter__() and __next__(). The __next__() method returns the next item in the sequence and raises a StopIteration exception when no more items are available.

Example of Using an Iterator

Here’s a basic example to illustrate how iterators work in Python:

# Define a list (which is an iterable)
my_list = [1, 2, 3, 4, 5]

# Get an iterator from the iterable
my_iterator = iter(my_list)

# Use the iterator to get items
print(next(my_iterator))  # Output: 1
print(next(my_iterator))  # Output: 2
print(next(my_iterator))  # Output: 3
print(next(my_iterator))  # Output: 4
print(next(my_iterator))  # Output: 5
# Trying to get the next item will raise StopIteration
# print(next(my_iterator))  # Uncommenting this will raise StopIteration


Custom Iterator Example

You can create your own iterator by defining a class with __iter__() and __next__() methods.

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

    def __iter__(self):
        return self

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

# Create an instance of MyNumbers
numbers = MyNumbers(1, 5)

# Get an iterator from the instance
numbers_iterator = iter(numbers)

# Iterate through the numbers
for number in numbers_iterator:
    print(number)  # Output: 1 2 3 4 5


Understanding Iteration Protocol

  1. __iter__() Method: This method returns the iterator object itself. It is called when the iter() function is used on an iterable.
  2. __next__() Method: This method returns the next value from the iterator. It is called by the next() function. When there are no more items to return, it should raise a StopIteration exception.


Iterating Over a List

Following examples shows how to iterate in List

my_list = ['a', 'b', 'c', 'd']
iterator = iter(my_list)

while True:
    try:
        item = next(iterator)
        print(item)
    except StopIteration:
        break


Creating a Fibonacci Iterator

Here's an example of a custom iterator for generating Fibonacci numbers

class Fibonacci:
    def __init__(self, max_count):
        self.max_count = max_count
        self.count = 0
        self.a, self.b = 0, 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.count >= self.max_count:
            raise StopIteration
        self.a, self.b = self.b, self.a + self.b
        self.count += 1
        return self.a

# Create a Fibonacci iterator
fib = Fibonacci(10)

# Iterate through Fibonacci numbers
for num in fib:
    print(num)  # Output: 1 1 2 3 5 8 13 21 34 55


Summary

  • Iterables: Objects that have an __iter__() method that returns an iterator.
  • Iterators: Objects with __iter__() and __next__() methods, capable of returning items one at a time from a collection.
  • Iteration Protocol: The combination of __iter__() and __next__() methods that allows you to traverse through elements in a collection.

By understanding and using iterators, you can efficiently handle sequences of data and create custom iteration behavior in your Python programs.