Reverse Python Lists: Beyond .reverse() and reversed()
Sometimes you need to process Python lists starting from the last element down to the first—in other words, in reverse order. In general, there are two main challenges related to working with lists in reverse:
To meet the first challenge, you can use either .reverse()
or a loop that swaps items by index. For the second, you can use reversed()
or a slicing operation. In the next sections, you’ll learn about different ways to accomplish both in your code.
Reversing Lists in Place
Like other mutable sequence types, Python lists implement .reverse()
. This method reverses the underlying list in place for memory efficiency when you’re reversing large list objects. Here’s how you can use .reverse()
: