In Python, the built-in range()
function is frequently used in loops to iterate over a sequence of numbers. While the built-in function is useful, it is limited to generating sequences of integers.
In this tutorial, we will learn how to create our own custom range function, named custom_range()
, which will extend the functionality of the original range()
and allow for floating-point numbers and other data types.
Step 1: Define the custom_range function
To create the custom_range()
function, we start by defining its basic structure. The function should take three parameters: start
, stop
, and step
. These correspond to the starting point of the range, the stopping point, and the step size between elements.
1 2 |
def custom_range(start, stop, step): pass # Leave this empty for now. |
Step 2: Implement the custom range logic
Next, we focus on implementing the logic that generates the desired range sequence. Using a while
loop, we continue adding the step size to the starting value until we reach the stopping point. For each iteration, we check whether the resulting value is within the desired range and yield it using the yield
keyword, effectively making our function a generator.
1 2 3 4 5 |
def custom_range(start, stop, step): current = start while current < stop: yield current current += step |
Step 3: Test the custom_range function with different data types
Now that our function is implemented, we need to verify that it works correctly for various data types. We will test it using integers, floating-point numbers, and strings.
1 2 3 4 5 6 7 8 9 10 11 |
print("Integers:") for i in custom_range(0, 10, 2): print(i) print("\nFloats:") for f in custom_range(0.0, 2.0, 0.5): print(f) print("\nStrings:") for s in custom_range(ord("a"), ord("f"), ord("b") - ord("a")): print(chr(s)) |
The above code should output the following:
Integers: 0 2 4 6 8 Floats: 0.0 0.5 1.0 1.5 Strings: a b c d e
Conclusion
With the custom_range()
function, we have successfully implemented a more versatile alternative to Python’s built-in range()
function that can handle various data types. This can make it easier to work with different data types within the same logic. Additionally, the use of generator functions in this implementation ensures that our custom range function is memory efficient.