Menu
Coddy logo textTech

Custom Range Iterator

Lesson 10 of 13 in Coddy's Python Iterators course.

challenge icon

Challenge

Easy

Create a custom iterator class called StepRange that generates a sequence of numbers with a custom step size. This iterator should mimic the behavior of Python's built-in range() function but with more flexibility in step sizes.

The StepRange class should:

  • Accept start, stop, and step parameters in its constructor
  • Implement the __iter__() method to return the iterator object itself
  • Implement the __next__() method to generate the next value in the sequence
  • Handle both positive and negative step sizes
  • Raise a StopIteration exception when the sequence is exhausted

After implementing the StepRange class, create an instance of it using the input values and print each generated number on a new line.

The following input will be provided:

  • Three space-separated integers representing start, stop, and step

Try it yourself

# Read input
start, stop, step = map(int, input().split())

class StepRange:
    def __init__(self, start, stop, step):
        self.start = start
        self.stop = stop
        self.step = step
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        # TODO: Implement the __next__() method
        pass

# Create an instance of StepRange
step_range = StepRange(start, stop, step)

# TODO: Iterate through the StepRange and print each value
# Remember to print each value on a new line

All lessons in Python Iterators