Python List - Reverse - Using reverse(), slicing
Python - Reverse a List
To reverse the order of items in a list, or simply said reverse a list, use reverse() method of List Class.
In this tutorial, we shall first discuss about the trivial reverse() function to reverse a Python List. Then we shall go through some of the unconventional approaches to reverse a list, for widening our Python knowledge.
Syntax of reverse()
The syntax of reverse() method is given below.
mylist.reverse()
Another method of reversing a list is using slicing. Following statement reverses and returns the resulting list.
reversed_list = mylist[::-1]
Examples
1. Reverse a given list of numbers using reverse()
In the following example, we have a List of numbers. We will reverse the list using reverse() method.
Python Program
# A list of numbers
mylist = [21, 5, 8, 52, 21, 87, 52]
# Reverse the list
mylist.reverse()
# Print the list
print(mylist)
Output
[52, 87, 21, 52, 8, 5, 21]
reverse() method directly updates the original list.
2. Reverse the list using slicing
In this example, we will use slicing technique and revere the given list.
Python Program
#list of numbers
mylist = [21, 5, 8, 52, 21, 87, 52]
#reverse list using slicing
mylist = mylist[::-1]
#print the list
print(mylist)
Output
[52, 87, 21, 52, 8, 5, 21]
Slicing does not modify the original list, but returns a reversed list.
3. Reverse a given list of strings
In this example, we reverse a list of strings.
Python Program
#list of strings
mylist = ['list', 'dict', 'set']
#reverse list
mylist.reverse()
#print the list
print(mylist)
Output
['set', 'dict', 'list']
Summary
In this tutorial of Python Examples, we learned how to reverse a Python List, with the help of well detailed example programs.