How to Create a Negative Range in Python?

Estimated read time 1 min read

In Python, you can create a negative range using the range() function in combination with a negative step value. Here is an example:

# Create a negative range from -10 to -1
my_range = range(-10, 0)

# Print the elements of the negative range
for i in my_range:
    print(i)

In this code, we create a negative range using the range() function with a start value of -10, an end value of 0 (excluded), and a default step value of 1. Since we want to create a negative range, we specify a negative step value implicitly. We then iterate over the elements of the negative range using a for loop and print each element. This should output the following:

-10
-9
-8
-7
-6
-5
-4
-3
-2
-1

You can adjust the start and end values of the negative range as needed, and also specify a different negative step value if necessary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply