How do I reverse a list or loop over it backwards?
There are a few ways to reverse a list in Python, depending on what you want to do with the reversed list.
There are a few ways to reverse a list in Python, depending on what you want to do with the reversed list.
If you want to reverse the elements of the list in place (i.e., modify the original list), you can use the reverse() method:
Reverse the elements of the list in place using the reverse method
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # prints [4, 3, 2, 1]
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
If you want to create a new list with the elements in reverse order, you can use slicing with a step of -1:
Create a reversed copy of the list using slicing
my_list = [1, 2, 3, 4]
reversed_list = my_list[::-1]
print(reversed_list) # prints [4, 3, 2, 1]Or using the list() and reversed() built-in functions:
Create a reversed copy of the list using reversed()
my_list = [1, 2, 3, 4]
reversed_list = list(reversed(my_list))
print(reversed_list) # prints [4, 3, 2, 1]Note that reversed() returns an iterator rather than a list, so wrapping it with list() creates a new list object.
To loop over a list backwards, you can use a for loop with a range object that counts down from the length of the list to 0, and use the index to access each element in the list:
Loop over a list backwards using a range object
my_list = [1, 2, 3, 4]
for i in range(len(my_list) - 1, -1, -1):
print(my_list[i])This will print the elements of the list in reverse order, so the output will be 4, 3, 2, 1.
Another way to loop over a list backwards would be to use the reversed() function within a for loop:
Loop over a list backwards using reversed()
my_list = [1, 2, 3, 4]
for element in reversed(my_list):
print(element)This will also produce the same result of 4, 3, 2, 1.