Reverse an array(list) using while loop Python

In this tutorial, we will learn writing python program to create an array (list in case of python) and return the reverse of elements stored in the array (list).

Problem Statement

Our program will first take the input of array (list) size and then the elements of the array (list) by the user. After applying some logic it will return the reverse of the input array (list).

For example:

Case 1: if the user inputs 4 as array (list) size and the array (list) elements as 1,2,3,4.

            The output should be 4,3,2,1.

Case 2: if the user inputs 5 as array (list) size and the array (list) elements as 9,8,7,6,5.

             The output should be 5,6,7,8,9.

Our logic to print an array(list) in reverse order using while loop

  • Our program will take input to fix the size of the array (list).
  • Create two empty lists.
  • Then our program will run for a ‘for loop’ to take the inputs from the user. The inputs will be the elements (or the content) of the array (list).
  • Then our program will use a while loop to add elements from the last of the list.

Python code to print an array(list) in reverse order using while loop

# taking the input from the user to fix the array size
size=int(input("Enter the number of elements you want in array: "))
# Create two empty lists
arr=[]
revArr=[]
# adding the elements to the list
for i in range(0,size):
    elem=int(input("Please give value for index "+str(i)+": "))
    arr.append(elem)
startIndex = 0;
lastIndex = size - 1;
# iterate the while loop till the lastindex 0
while (lastIndex>=0):
    revArr.append(arr[lastIndex])
    startIndex+=1
    lastIndex-=1
# printing the reversed list
print("Array in reverse order")
for i in range(0,size):     
    print(revArr[i],end=' ') 

Output

Enter the number of elements you want in array: 5
Please give value for index 0: 4
Please give value for index 1: 6
Please give value for index 2: 4 
Please give value for index 3: 7
Please give value for index 4: 4
Array in reverse order
4 7 4 6 4 
What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now