How can you reverse a list or an array with Python? You’ll learn the different approaches in this article.
Create a Copy With a for Loop
While Python’s for loop is more verbose, it might be handy in some cases. For instance, it provides more flexibility when performing complex logic at some points in the reverse operation.
When using an indented for loop, the common approach is to iterate through the original list in reverse order. Starting with the final element, each iteration then appends the previous element to a new list.
Given a list of integers between one and nine as an example, here’s how to reverse an array using an indented for loop:
Reverse a List or an Array Using List Comprehension
A list comprehension produces shorter code. And there’s no need for a temporary variable because list comprehension acts on a list in place.
To carry out the previous operation, using a list comprehension:
Use the Slice Operator
The list slice operator is pretty straightforward, although it has some limitations. For example, you might not be able to customize the output as you would when using a for loop.
Here’s how to reverse a list using the slice operator:
The [::-1] syntax is a clever shortcut that results in a reversed list. It actually means “copy every element of the list, starting from the end and counting backward” — i.e. “reverse it”!
Use an Array’s reverse Method
This is another method that acts in place: it modifies the original array. This can be a shortcoming since you can’t keep the previous list for other operations.
Here’s how to reverse an array using the reverse method:
Use the reversed Function
The reversed function iterates over a list, array, or any other sequence and returns its reversed copy. However, you need to explicitly declare the reversed output as a list.
This is how it works:
Getting Creative With Arrays
Arrays or lists are common ways to store data. Depending on your goal, you might want to present data to the client in reverse order. One way to do this is to reverse the array or list before rendering it. As you’ve seen, there are a couple of ways to invert a list in Python. Choose what works best for you and aligns with your logic for a specific problem.
You might also want to see how to reverse an array in other programming languages to understand the background logic better.