Javaexercise.com

Python Program To Print List In Reverse Order

Python List is a data structure that stores elements in linear order. When we traverse the list elements then it produce the result in the same manner in which items are stored.

To access list elements in reverse order, python provides reversed() function. The reversed() function is used to iterate any iterable (list, tuple, dictionary) in reverse order. So in this tutorial, we will use reversed() function, range() function and sorted() function to access list elements in reverse order. Lets see some example.

 

Python Program: Reverse List Elements using reversed() Function

In this program, we are using reversed() function to print list elements in reverse order. It is built-in function that helps us to reverse a list without writing our custom program logic. 

# Take a list
listItems = [2,3,6,8,11,2,5,6,8,4,3]
# Print the list
print("List items:\n",listItems)
# Python reversed method
reverseList = reversed(listItems)
print("List items in reverse order:")
for elements in reverseList:
	print(elements,end=' ')

Output:

List items:
[2, 3, 6, 8, 11, 2, 5, 6, 8, 4, 3]
List items in reverse order:
3 4 8 6 5 2 11 8 6 3 2 

 

Python Example : Reverse List Elements Using range() Function

We can use range() function to traverse elements in reverse order by setting its start and end argument. In the below example, we started range from end of the list and decrease the index by one. So that it can iterate in reverse order. Here is the example.

# Take a list
listItems = [2,3,6,8,11,2,5,6,8,4,3]
# Print the list
print("List items:\n",listItems)
# Get length of list
listlen = len(listItems)-1
print("List items in reverse order:")
for i in range(listlen,-1,-1):
	print(listItems[i],end=' ')

Output:

List items:
[2, 3, 6, 8, 11, 2, 5, 6, 8, 4, 3]
List items in reverse order:
3 4 8 6 5 2 11 8 6 3 2

 

 

Python Example : Fetch List Items in Reverse Order using sorted() Function

Python sorted() function is used to sort the list elements. We can use it to sort elements in both ascending and descending order. Here we are using it to sort elements in descending order by setting reverse = true. It is helpful if list items are in sorted order.

# Take a list
listItems = [2,3,6,8,11,20,40]
# Print the list
print("List items:\n",listItems)
# sorting list in descending order
newList = sorted(listItems, reverse = True)
print("List items in reverse order:")
for elements in newList:
	print(elements, end=' ')

Output:

List items:
[2, 3, 6, 8, 11, 20, 40]
List items in reverse order:
40 20 11 8 6 3 2

Note: This approach is helpful only if list elements are in sorted order.

 


Conclusion

Well, in this topic, we learnt to write programs to print Python list elements in reverse order. We used reversed(), sorted() and range() functions to get elements in reverse order.