How to make a cycle in the reverse order python

Create a reverse loop in Python with an example. A step-by-step guide to looping through a list in reverse order.

Reversing a Cycle in Python

Python provides various ways to reverse a cycle. We can use the reversed() function, slice operator, and a for loop to reverse a cycle.

The reversed() function is the simplest way to reverse a cycle. We just have to pass the cycle as an argument to the reversed() function and get the reversed cycle as an iterator.

numbers = [1, 2, 3, 4, 5]

# using reversed()
rev_nums = reversed(numbers)

# printing the reversed cycle
print(list(rev_nums))

# Output
[5, 4, 3, 2, 1]

The slice operator can also be used to reverse a cycle. We have to use the step parameter of the slice operator. By setting the step parameter to -1, we can reverse the cycle.

numbers = [1, 2, 3, 4, 5]

# using slice operator
rev_nums = numbers[::-1]

# printing the reversed cycle
print(rev_nums)

# Output
[5, 4, 3, 2, 1]

We can also use a for loop to reverse a cycle. We just have to iterate over the cycle in reverse order and add its items to a list.

numbers = [1, 2, 3, 4, 5]

# using for loop
rev_nums = []

for num in range(len(numbers)-1, -1, -1):
    rev_nums.append(numbers[num])

# printing the reversed cycle
print(rev_nums)

# Output
[5, 4, 3, 2, 1]

These are the three ways to reverse a cycle in Python. We can use any one of these methods to reverse a cycle in Python.

Answers (0)