Python - Print list in reverse order
Python - Print list in reverse order
In Python, you can print the elements in a list in reverse order using List slicing, a For loop with reversed list, or a While loop with a counter for index that traverses from ending of the list to starting of the list.
In this tutorial, we shall go through some examples where we take a list of elements, and print the elements in the list in reverse order to standard console output.
1. Print list in reverse order using List Slicing in Python
List slicing expression with a negative step returns an iterator that iterates from end of the list to start of the list.
Pass the reversed iterator (the slice expression) as argument to print method, and then it prints the given list in reverse order.
Python Program
x = ['apple', 'banana', 'cherry']
print(x[::-1])
Output
['cherry', 'banana', 'apple']
The elements in list are printed in reverse order.
2. Print list in reverse order using For loop and List Slicing in Python
List slicing expression with a negative step returns an iterator that iterates from end of the list to start of the list.
If x
is given list, then the slicing expression x[::-1]
returns the reversed iterator.
Then you can use a For loop to iterate over the reversed iterator of the given list. In the For loop, print the element.
Python Program
x = ['apple', 'banana', 'cherry']
for element in x[::-1]:
print(element)
Output
cherry
banana
apple
The elements in list are printed in reverse order.
3. Print list in reverse order using While loop with counter in Python
In the following program, we use While loop to iterate over the given list. We shall maintain a counter index that starts at length of list minus one before while loop, and decrements by one for each iteration of the loop, thus mimicking the index of elements in the list from ending to starting of list.
Inside the While loop, we shall print the list element fetched using the index.
Python Program
x = ['apple', 'banana', 'cherry']
index = len(x) - 1
while index >= 0:
element = x[index]
print(element)
index -= 1
Output
cherry
banana
apple
Summary
In this tutorial, we have seen how to print list elements in reverse order using List slicing, For loop with list slicing, or a While loop with counter. We have gone through examples that use each of these approaches.