This succinct, example-based article shows you the best and most Pythonic approaches to reversing a given list in Python (in terms of performance and code readability).
Using the reverse() method
The reverse()
method reverses the order of the elements in your list in place, meaning it modifies the original list. No new list object is created, which saves memory.
This example reverses a list of numbers:
# a list of integers and floats
numbers = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)
Output:
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]
Another example that demonstrates how the reverse()
method works with a list of mixed data types:
# a list of mixed data types
my_list = [1, "Hello", 3.4, True, "World"]
my_list.reverse()
print(my_list)
Output:
['World', True, 3.4, 'Hello', 1]
reversed()
is a built-in Python method specially designed for the purpose of reversing a list, so it is very efficient and concise.
Using the reversed() function
In case you want to keep your original list intact, use the reversed()
function.
The reversed()
function (not to be confused with the reverse()
method) takes an iterable as an argument and returns an iterator of the elements in reverse order. This function can work with any iterable, not just lists. It does not modify the original iterable.
Example:
my_list = ["morning", "noon", "evening", "night"]
reversed_iterable = reversed(my_list)
reversed_list = list(reversed_iterable)
print(reversed_list)
Output:
['night', 'evening', 'noon', 'morning']
This method requires an extra step, which is to convert the resulting iterable to a list.
Using slicing
You can also use a slicing notation with a negative step value ([::-1]
) to create a new list whose elements are in reversed order in comparison with the input list.
Example:
my_list = ['welcome', 'to', 'sling', 'academy']
reversed_list = my_list[::-1]
print(reversed_list)
Output:
['academy', 'sling', 'to', 'welcome']
This approach is shorter than the previous approach.
Conclusion
We’ve covered the best techniques to invert the order of elements in a list in Python. They are both efficient and have neat syntax. Choose the ones that suit your needs to go with. Happy coding & have a nice day!