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, andstep. - Use a
whileloop to yield values starting fromstart, incrementing bystepeach time, and stopping before reachingend. - Support both positive and negative step values.
- Use the
yieldkeyword — notreturn— 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:
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.
Key Concepts:
- A generator function uses
yieldinstead ofreturn. Each call toyieldpauses 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
forloop ornext()call). - The
whilecondition must check the direction ofstepto 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.