Skip to content

Effortlessly Reverse Range in Python

[

Python range(): Represent Numerical Ranges

A range is a Python object that represents an interval of integers. Usually, the numbers are consecutive, but you can also specify that you want to space them out. You can create ranges by calling range() with one, two, or three arguments, as the following examples show:

Python

>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(1, 7))
[1, 2, 3, 4, 5, 6]
>>> list(range(1, 20, 2))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

In each example, you use list() to explicitly list the individual elements of each range.

Construct Numerical Ranges

In Python, range() is built-in, so you don’t need to do any preparations before calling it. It returns a range object that you can put to use. There are three different use cases for range() based on the number of arguments you provide:

  1. Ranges counting from zero
  2. Ranges of consecutive numbers
  3. Ranges stepping over numbers

Let’s look at each use case individually.

Count From Zero

When you call range() with one argument, it creates a range that counts from zero and stops right before the specified number. Here’s an example:

Python

>>> range(5)
range(0, 5)

In this example, the range created is from zero to five (exclusive).

Count From Start to Stop

To create a range that starts at a specific number and stops right before another number, you can provide two arguments to range(). Here’s an example:

Python

>>> range(1, 7)
range(1, 7)

This creates a range from 1 to 6 (inclusive).

Count From Start to Stop With a Step

If you want to create a range that starts at a specific number, stops before another number, and increments by a specific step, you can provide three arguments to range(). Here’s an example:

Python

>>> range(1, 20, 2)
range(1, 20, 2)

This creates a range from 1 to 19 (inclusive) with a step of 2. The resulting range includes all odd numbers between 1 and 19.

Use Python’s range() Function to Create Specific Ranges

The range() function in Python is a versatile tool for creating specific ranges of numbers. By specifying the start, stop, and step parameters, you can create a range that suits your needs.

Handle Ranges Over Negative Numbers

You can use the range() function with negative numbers as well. For example, to create a range that counts from -5 to 0, you can do the following:

Python

>>> list(range(-5, 1))
[-5, -4, -3, -2, -1, 0]

This creates a range that includes all negative numbers from -5 to 0.

Work With an Empty Range

If you provide the same start and stop arguments to range(), it will create an empty range. For example:

Python

>>> list(range(1, 1))
[]

This creates an empty range since there are no numbers greater than or equal to 1 and less than 1.

Count Backward With Negative Steps

You can also count backward by providing a negative step value to range(). For example, to count from 10 to 1 in reverse order, you can do the following:

Python

>>> list(range(10, 0, -1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

This creates a range that includes all numbers from 10 to 1 in reverse order.

Loop Through Ranges or Use an Alternative

In Python, you can use the for loop to iterate over a range and perform an operation for each element. For example:

Python

for num in range(5):
print(num)

This will print the numbers 0 to 4.

However, in some cases, there are alternative ways to achieve the same outcome. Here are a few alternatives to consider:

Repeat an Operation

If you want to repeat the same operation a specific number of times, you can use the range() function in combination with the for loop. For example:

Python

for _ in range(5):
print("Hello, world!")

This will print “Hello, world!” five times.

Loop Directly Over the Iterator Instead

Instead of using range() and indexing the elements, you can directly loop over the iterator itself. For example:

Python

for num in range(1, 10):
print(num)

This will print numbers 1 to 9.

Use enumerate() to Create Indices Instead

If you need both the elements of a range and their indices, you can use the enumerate() function. For example:

Python

for idx, num in enumerate(range(1, 10)):
print(f"Index: {idx}, Number: {num}")

This will print the index and number of each element in the range.

Use zip() for Parallel Iteration Instead

If you have multiple iterables and want to iterate over them in parallel, you can use the zip() function. For example:

Python

fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "red"]
for fruit, color in zip(fruits, colors):
print(f"Color of {fruit} is {color}")

This will print the fruit and its corresponding color.

Explore Other Features and Uses of Ranges

Apart from creating specific numerical ranges and using them in loops, there are many other features and uses of ranges in Python.

Access Individual Numbers of a Range

You can access individual numbers within a range by indexing the range object using square brackets. For example:

Python

my_range = range(1, 10)
print(my_range[3]) # Prints 4

This will print the fourth element of the range.

Create Subranges With Slices

You can create subranges within a range by using slices. For example:

Python

my_range = range(1, 10)
print(my_range[2:6]) # Prints range(3, 7)

This will create a subrange from the third element to the sixth element of the range.

Check Whether a Number Is a Member of a Range

You can use the in operator to check if a number is a member of a range. For example:

Python

my_range = range(1, 10)
print(5 in my_range) # Prints True

This will check if the number 5 is in the range and print True.

Calculate the Number of Elements in a Range

To find the number of elements in a range, you can use the len() function. For example:

Python

my_range = range(1, 10)
print(len(my_range)) # Prints 9

This will print the total number of elements in the range.

Reverse a Range

You can reverse the order of a range by using the reversed() function. For example:

Python

my_range = range(1, 10)
reversed_range = reversed(my_range)
print(list(reversed_range)) # Prints [9, 8, 7, 6, 5, 4, 3, 2, 1]

This will print the range in reverse order.

Create a Range Using Integer-Like Parameters

Python’s range function allows you to create ranges using integer-like parameters. For example, you can use a variable or an expression that evaluates to an integer as arguments for range(). Here’s an example:

Python

start = 1
stop = 10
step = 2
my_range = range(start, stop, step)
print(list(my_range)) # Prints [1, 3, 5, 7, 9]

This demonstrates how you can use variables to define the start, stop, and step parameters of a range.

Conclusion

The Python range() function is a versatile tool for representing numerical ranges. By specifying the start, stop, and step parameters, you can create ranges that suit your specific needs. Whether you want to loop over a range, repeat an operation, or work with specific elements of a range, understanding the range() function is essential for writing efficient and concise Python code.

Note: This article was rewritten for educational purposes and does not cite the original source or original author.