Python Iterators

Welcome to The Coding College, your hub for mastering Python! In this guide, we’ll explore Python Iterators, a fundamental concept for working with sequences like lists, tuples, and strings. Understanding iterators will help you write efficient, Pythonic code.

What Are Iterators in Python?

An iterator is an object in Python that allows you to traverse a sequence, such as a list or tuple, one element at a time.

  • Iterable: An object capable of returning its elements one at a time (e.g., lists, tuples, dictionaries).
  • Iterator: An object with a method __next__() to fetch the next item.

Key Features of Iterators

  1. Lazy Evaluation: Iterators compute elements on demand, saving memory.
  2. Custom Traversal: You can define how to iterate over objects.
  3. Infinite Sequences: Generate values as needed, useful for tasks like Fibonacci series.

The iter() and next() Functions

The iter() Function

The iter() function converts an iterable (like a list) into an iterator.

my_list = [1, 2, 3]  
my_iter = iter(my_list)  
print(my_iter)  # Output: <list_iterator object at 0x...>  

The next() Function

The next() function retrieves the next element from an iterator.

print(next(my_iter))  # Output: 1  
print(next(my_iter))  # Output: 2  
print(next(my_iter))  # Output: 3  

Iterators vs. Iterables

  • Iterable: An object with an __iter__() method that returns an iterator.
  • Iterator: An object with both __iter__() and __next__() methods.

Example: Iterable and Iterator

my_tuple = (10, 20, 30)  # Iterable  
my_iter = iter(my_tuple)  # Iterator  

print(next(my_iter))  # Output: 10  
print(next(my_iter))  # Output: 20  

Custom Iterators

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

Example: Custom Iterator

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:  
            value = self.current  
            self.current += 1  
            return value  
        else:  
            raise StopIteration  

numbers = MyNumbers(1, 5)  
for num in numbers:  
    print(num)  

Output:

1  
2  
3  
4  
5  

Infinite Iterators

Iterators can generate an infinite sequence, but be cautious to avoid infinite loops.

import itertools  

infinite_numbers = itertools.count(start=1, step=1)  
for num in infinite_numbers:  
    if num > 5:  
        break  
    print(num)  

Output:

1  
2  
3  
4  
5  

The StopIteration Exception

When an iterator reaches the end of a sequence, it raises the StopIteration exception to signal that there are no more items.

Example

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

    def __iter__(self):  
        return self  

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

for num in MyRange(1, 4):  
    print(num)  

Output:

1  
2  
3  

Itertools: Advanced Iterators

The itertools module provides advanced iterator tools.

Example: itertools.cycle()

Repeats a sequence indefinitely.

import itertools  

cycle_iter = itertools.cycle(["A", "B", "C"])  
for i in range(6):  
    print(next(cycle_iter))  

Output:

A  
B  
C  
A  
B  
C  

Exercises to Practice Python Iterators

Exercise 1: Basic Iterator

Create a custom iterator class to iterate through numbers from 10 to 20.

Exercise 2: Infinite Iterator

Create an infinite iterator that generates even numbers starting from 2.

Exercise 3: Fibonacci Iterator

Write a custom iterator to generate the Fibonacci sequence.

Why Learn Iterators with The Coding College?

At The Coding College, we make Python concepts easy to understand. Mastering iterators will enhance your coding efficiency and prepare you for advanced topics like generators and asynchronous programming.

Conclusion

Python Iterators are powerful tools for managing sequences in a memory-efficient and Pythonic way. By practicing the examples and exercises here, you’ll gain a deep understanding of how iterators work and how to use them effectively.

Leave a Comment