In this post, I will show you different techniques for how to reverse a list in python. So without wasting any further time let’s get started.
Different Ways of How to Reverse a List in Python
Let’s look at different ways to reverse a list.
1. By Using list.reverse() Method
The reverse method of the python list does not take any argument and reverse the order of all its elements.
it does not return any value instead, it updates the existing list
>>> items = [0,1,2,3,4,5] >>> items.reverse() >>> items [5, 4, 3, 2, 1, 0]
2. By Using reversed() Builtin Function
reversed() is the builtin function that takes an iterable as an argument and reverses its order and returns an iterator.
>>> items = [0,1,2,3,4,5] >>> list(reversed(items)) # iterator converted to list [5, 4, 3, 2, 1, 0]
3. By Using Slicing
In this code example we have used slicing to reverse a string.
>>> items = [0,1,2,3,4,5] >>> items[::-1] [5, 4, 3, 2, 1, 0]
4. By Using While Loop
In the following code snippet, we have used a while-loop to reverse a string.
Here is the algorithm.
- We first defined an empty list to store the reversed values.
- Then we obtain the length of the input list.
- We then define a while loop to run until the variable ‘l’ is greater than 0.
- Inside the body of the while loop, we first append an element at index l-1 to the list then we decrease the value of l by 1.
- Finally, we return the reversed list to the caller.
# program for how to reverse a list in python def reverse(items): final =  # list to store reversed list l = len(items) # get the length of list while l > 0: # run while loop until l is greater than 0 final.append(items[l-1]) # add item to list l-=1 # decrease l by 1 return final items = [0,1,2,3,4,5] print(reverse(items))
[5, 4, 3, 2, 1, 0]
Here is the summary of whole tutorial in one picture.
Also read about how to revese a string in python.