58. Custom Iterables with __iter__ and __next__

Here are 10 Python code snippets that demonstrate how to implement custom iterables using the __iter__ and __next__ methods:

1. Simple Iterable Class

A basic class that defines an iterable object with a custom __iter__ and __next__ method.

Copy

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

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

countdown = Countdown(5)
for number in countdown:
    print(number)
# Output: 5 4 3 2 1

This snippet defines a Countdown class that counts down from a starting number, printing each value in turn until it reaches 1.


2. Fibonacci Sequence Iterable

Creating an iterable that generates Fibonacci numbers.

Copy

This example defines an iterable that generates Fibonacci numbers up to a specified limit.


3. Even Numbers Iterable

Creating an iterable for even numbers within a specified range.

Copy

This code creates an iterable that generates even numbers between start and end.


4. Reverse String Iterable

An iterable that iterates through a string in reverse.

Copy

This snippet creates an iterable that iterates over a string in reverse order.


5. Range-Like Iterable

Custom range class that behaves like Python’s built-in range.

Copy

This defines a custom iterable that behaves like range(start, stop, step).


6. Prime Numbers Iterable

An iterable that generates prime numbers.

Copy

This example creates an iterable that generates prime numbers up to a specified limit.


7. Square Numbers Iterable

Creating an iterable that generates square numbers.

Copy

This creates an iterable for square numbers from start to end.


8. Character Repeated Iterable

An iterable that repeats a character multiple times.

Copy

This iterable repeats a character a specified number of times.


9. Matrix Row Iterator

Creating an iterable to traverse rows of a matrix.

Copy

This snippet defines an iterable that iterates through the rows of a matrix.


10. Random Number Iterable

An iterable that generates random numbers within a range.

Copy

This creates an iterable that generates random numbers within a specified range for a given count.


These examples demonstrate how to create custom iterables in Python by implementing the __iter__ and __next__ methods. This allows you to control the iteration behavior for any object and use it in for-loops or any other iterable context.

Last updated