← Previous Module 11: Iterators & Generators Next →
Statement
Solution

Python Exercise 11.1: Custom Range

Generators are a memory-efficient way to produce sequences on demand. In this exercise, you will build a generator function my_range(start, end, step) that mimics the behaviour of Python's built-in range().

Your generator function should:

  • Accept three parameters: start, end, and step.
  • Use a while loop to yield values starting from start, incrementing by step each time, and stopping before reaching end.
  • Support both positive and negative step values.
  • Use the yield keyword — not return — to produce each value.

Once defined, use your generator to print:

  • All values from my_range(1, 10, 2) on one line, space-separated.
  • All values from my_range(10, 0, -3) on one line, space-separated.

Sample Output:

Input
Output
(no input required)
1 3 5 7 9 10 7 4 1

Solution

The key is using yield inside a while loop. The loop condition must account for the sign of step so the generator works correctly in both directions.

def my_range(start, end, step): current = start while (step > 0 and current < end) or (step < 0 and current > end): yield current current += step print(*my_range(1, 10, 2)) print(*my_range(10, 0, -3))

Key Concepts:

  • A generator function uses yield instead of return. Each call to yield pauses the function and returns the value to the caller.
  • The function resumes from where it left off the next time the caller asks for a value (e.g. in a for loop or next() call).
  • The while condition must check the direction of step to avoid an infinite loop when stepping negatively.
  • print(*my_range(...)) unpacks the generator and prints all values space-separated in one line.
  • Generators are memory-efficient: they produce one value at a time instead of building the full list in memory.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top