Python program to print an array(list) in reverse order

In this tutorial we will learn writing program in python 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). And 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

  • Our program will take input to fix the size of the array (list).
  • 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 reverse the elements using the range function in for loop.

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

# Taking the input from the user to fix the array size
size = int(input("Enter the number of elements you want in array: "))

# Creating an empty list
arr = []

# Adding the elements of the list by taking inputs from the user
for i in range(0, size):
    elem = int(input("Please give value for index " + str(i) + ": "))
    arr.append(elem)

print("Array in reverse order:")

# Reversing the list and printing it
for i in range(size - 1, -1, -1):     
    print(arr[i], end=' ')

Output

Enter the number of elements you want in array: 3
Please give value for index 0: 1
Please give value for index 1: 2
Please give value for index 2: 3
Array in reverse order:
3 2 1

Explanation

The input list is [1, 2, 3 ] which is given by the user. The range() function with arguments (size-1,-1,-1) will read the elements of the array from the end of the list. So the output will be printed from the last element of the list. so the output will be 3 2 1.

What did you think?

Similar Reads

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