Reverse Order

You can reverse the order of a list by calling the reverse() method on the list. This method changes the order of the list permanently, but you can revert to the original order anytime by applying reverse() to the same list a second time.

File: reverse.py:

numbers = list(range(1, 6))
print(numbers)

numbers.reverse() # reverse the list
print(numbers)

numbers.reverse() # reverse the list again
print(numbers)

The first print statement outputs the original numbers list.

[1, 2, 3, 4, 5]

Note the way we created this list. range(1, 6) creates an iterator that produces the numbers 1 through 5 (6 is not included). Then the list() function converts the iterator to a list.

The first call to reverse() changes the order of the list permanently. This can be seen in the output:

[5, 4, 3, 2, 1]

The second call to reverse() changes the order of the list back to the original order:

[1, 2, 3, 4, 5]

As it was the case with sorting we can also reverse the order of a list temporarily by using the reversed() class.

reversed_numbers: reversed = reversed(numbers)

One important point here is that reversed() produces an iterator. We can convert it to a list by using the list() function.

If we now print it:

print(list(reversed_numbers))

we get numbers in reverse order:

[5, 4, 3, 2, 1]

Note, that the original list, numbers, is not modified.

In place reversal is usually more efficient than temporary reversal. On the other hand, temporary reversal is safer because it does not modify the original list. In addition, temporary reversal is lazy, meaning it does not perform any work until it is needed.