Last Updated on June 17, 2021 by Roshan Parihar
In this tutorial, learn how to change or reverse list elements using Python. The short answer is: use the Python reverse()
function to reverse the order of the list elements.
The reverse method changes the order of the list elements. You can change the location of the list elements and print the elements from last to start. You can also use the Python loop to change the order of the list elements.
How to Reverse List Element With Python Reverse()
If you want to change the order of the list elements, you have to use the Python reverse()
. Use the list variable followed by the reverse function to reverse the order.
See the example below to change the order of the list elements.
1 2 3 |
myList = ["one", "two", 37, "four", 51]; myList.reverse(); print(myList); |
Output
The above example prints the list elements in the reversed order. You have to use the above-given example to change your list elements order.
However, you can learn and use the loop to change the order of the list elements in the next section.
Change Position of List Items With For Loop and Reversed() in Python
To reverse the list elements, you have to use Python for loop and reversed()
function. You can use the below-given example to learn this method as per your requirement.
1 2 3 |
myList = ["one", "two", 37, "four", 51]; for x in reversed(myList): print(x); |
Output
four
37
two
one
The above example showing the elements printed the output in reverse order. The loop method prints the reversed elements in the output with a single element in a single line.
You can also use this method to access the list elements in reverse order.
Change Order of List Elements With Slice Operator
In addition to the above all methods, you can also use the slice operator to reverse the list order. To perform this, you have to use the below-given example and change the list with your list.
1 2 3 |
myList = ["one", "two", 37, "four", 51]; rev_list = myList[::-1]; print(rev_list); |
Output
The above examples showing the same output as you get with the reverse()
function. The example store the reversed list to the other variable. After that, it prints the reversed list using the print statement of Python.
DOWNLOAD Free PYTHON CHEAT SHEET
You may also like to read
- Learn how to create a list variable in Python
- Append or insert elements to list in Python
- Get list element by index in Python
- how to check if the list is empty or not using Python
I hope you like this post on how to reverse the list elements in Python.