In this article let's learn how to create a list and display all the list items in reverse order. I will use the list containing integers for demo purposes if you require any other type you can modify the program accordingly.
There are two ways to solve this. I'll explain both the types below.
Write A Python Script To Create A List And Display The List Element In Reverse Order
Let's take a variable named length and ask a user to enter the list length. Take another variable named as numbers Initialize it to an Empty list, this will be used to Store the list of numbers
Using for loop iterate from 0 to N (list length) and then ask user to enter the list items and then Append the items to numbers list
length = int(input("Enter List Length : "))
numbers = []
for _ in range(length):
temp = int(input("Enter List Item : "))
numbers.append(temp)
Now using a print statement displays a user-friendly message and using the for loop and string slicing method print all the items of a list in reverse order. Use the slicing method that is [::-1] to reverse a list containing numbers
print("Numbers in reverse order is ...")
for item in numbers[::-1]:
print(item)
The list can also be reversed using the while loop, take an index variable and set it to -1 and iterate infinitely. Use the try and except block, try to print the list item of index if the index error occurs break the infinite while loop as shown below.
print("Numbers in reverse order is ...")
index = -1
while True:
try:
print(numbers[index])
except IndexError:
break
index = index -1
Python Code 1
====================
length = int(input("Enter List Length : "))
numbers = []
for _ in range(length):
temp = int(input("Enter List Item : "))
numbers.append(temp)
print("Numbers in reverse order is ...")
for item in numbers[::-1]:
print(item)
Python Code 2
=====================
length = int(input("Enter List Length : "))
numbers = []
for _ in range(length):
temp = int(input("Enter List Item : "))
numbers.append(temp)
print("Numbers in reverse order is ...")
index = -1
while True:
try:
print(numbers[index])
except IndexError:
break
index = index -1
Output
==============
Enter List Length : 5
Enter List Item : 1
Enter List Item : 2
Enter List Item : 3
Enter List Item : 4
Enter List Item : 5
Numbers in reverse order are ...
5
4
3
2
1
Output
============
Enter List Length : 7
Enter List Item : 12
Enter List Item : 32
Enter List Item : 45
Enter List Item : 56
Enter List Item : 78
Enter List Item : 89
Enter List Item : 100
Numbers in reverse order are ...
100
89
78
56
45
32
12
Conclusion
==================
Execute the programs provided above by providing random integer values as an input to the Python program and note down the results. modify the above Python program to accept string values, add list items and print them in the reverse.
Comment it down below if you have any suggestions to improve the Python program.
0 Comments