In this tutorial, you will learn to reverse a list in Python using For loop with code examples.
Using the for loop can be a little intimidating if you are new to the Python programming language. In Python, however, you can easily reverse a list by utilizing the For Loop. All you are required to do is make sure how to keep the index check in reverse order.
Using For Loop To Reverse A List In Python
Let us see in the below code example the usage of For Loop to reverse a list in Python.
#Initializing a List with Values inputList = [1,2,3,4,5] getSize = len(inputList) reversedList = [] #Using For Loop to Reverse inputList for i in range(0, getSize): #adding the element in reverse order reversedList.append(inputList[getSize-i-1]) #Printing the Reversed List print(reversedList)
Output:
[5, 4, 3, 2, 1]
As you can see in the example code above, I was able to reverse a list by utilizing the For loop. You must first obtain the length of the list, after which you must separate the loop range “i” from the rest of the list and then obtain the value at the corresponding index in the list.
Alternatively, Use Reverse Function
If you do not want to use the for loop for the above problem then you can alternatively use the inbuilt function reverse() in Python. This will simplify be the code lines and also will have less number of code lines.
Let us see in the below code example the use of the reverse() function in Python.
#Initializing a List with Values inputList = [1,2,3,4,5] #Using the reverse Function to reverse a List inputList.reverse() #Printing The Reverse List print(inputList)
Output:
[5, 4, 3, 2, 1]
Wrap Up
I hope you were able to grasp the concept of looping through a list in Python and reversing the process. Please see the list below for two different methods from which you can select the one that best suits your needs.
Let me know in the comment section if you need any other method added here. I would love to help you as soon as possible.
If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.
Further Read: