Reverse a Range in Python with Examples

How to reverse a range in Python? There are several ways to reverse the range of numbers, for example, by using the reversed(), and sorted() built-in functions and by iterating using for loop and printing the elements in reverse order.

1. Range Introduction

2. Reverse Range using reversed()

The reversed() is a built-in function in python that will reverse any iterable object including range. This function takes the range as a parameter and returns the range_iterator, To reverse the range you need to pass the range object as a parameter to this method.

2.1 Syntax

Following is the syntax.


# Syntax
reversed(myrange)

Here, myrange is the input range.

2.2 Reverse Python Range Example

In this example, let’s create a python range between 0 to 10, and let’s reverse the range using the reversed() function.

Note that this function returns the <code>range_iterator, so to print the reversed order range, you can convert it to the list using list().


# Create range of numbers
myrange = range(0,10)
print("Actual Range", myrange)

# Reverse range 
result = reversed(myrange)

# Type of reversed range
print("Type: ",type(reversed(myrange)))

# Print reverse range
print("Reversed Range", list(result))

This example yields the below output.

python reverse range

3. Reverse Range using sorted() Function

The sorted() is also a built-in function that is used to sort the elements of the iterator including a list and returns the iterator object. To get the object in usable format use list() which converts it to the list.

3.1 Syntax

Following is the syntax


# Syntax
sorted(myrange, reverse=True)

Here myrange is the range that you preferred to sort. Use reverse=True to sort in reverse order

3.2 Reverse Range using sorted() Example

Python sorted() function is used to sort the elements, by using its reverse parameter we can get the range in reverse order.


# Create range of numbers
myrange = range(0,5)
print("Actual Range: ", myrange)

# Reverse range 
result = sorted(myrange, reverse=True)

# Type of reversed range
print("Type: ",type(result))

# Print reverse range
print("Reversed Range: ", list(result))

This example yields the below output.

python range reversed

4. Using for loop


# Create range of numbers
myrange = range(0,5)
print("Actual Range: ", myrange)

# Get range in reversed order
for x in range(5,0,-1):
    print(x)

Yields below output.

Conclusion

In this article, you have learned how to reverse the range in Python by using the built-in functions reversed() and sorted(). Besides these, you can also print the range in reverse order by using for loop.

NNK

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply