Table of Contents
In this tutorial, we will learn about the Python List reverse() method with the help of examples.
The reverse() method reverses the elements of the list.
Example
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# reverse the order of list elements
prime_numbers.reverse()
print('Reversed List:', prime_numbers)
# Output: Reversed List: [7, 5, 3, 2]
1. Syntax of List reverse()
The syntax of the reverse() method is:
list.reverse()
2. reverse() parameter
The reverse() method doesn’t take any arguments.
3. Return Value from reverse()
The reverse() method doesn’t return any value. It updates the existing list.
4. Example 1: Reverse a List
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
# List Reverse
systems.reverse()
# updated list
print('Updated List:', systems)
Output
Original List: ['Windows', 'macOS', 'Linux'] Updated List: ['Linux', 'macOS', 'Windows']
There are other several ways to reverse a list.
5. Example 2: Reverse a List Using Slicing Operator
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
# Reversing a list
# Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]
# updated list
print('Updated List:', reversed_list)
Output
Original List: ['Windows', 'macOS', 'Linux'] Updated List: ['Linux', 'macOS', 'Windows']
6. Example 3: Accessing Elements in Reversed Order
If you need to access individual elements of a list in the reverse order, it’s better to use the reversed() function.
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
# Printing Elements in Reversed Order
for o in reversed(systems):
print(o)
Output
Linux macOS Windows
Related posts:
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python min()
Python strftime()
Python Recursion
Python Program to Make a Simple Calculator
Python Program to Check Prime Number
Python complex()
Python Program to Convert Kilometers to Miles
Python datetime
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Calculate the Area of a Triangle
Python Program to Check if a Number is Positive, Negative or 0
Python String expandtabs()
Python Program to Count the Number of Digits Present In a Number
Python Program to Convert Celsius To Fahrenheit
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python String ljust()
Python Tuple index()
Python String index()
Python String isalpha()
Python sorted()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Type Conversion and Type Casting
Python String center()
Python Set union()
Python Program to Print Hello world!
Remove All Occurrences of a Specific Value from a List
Python File I/O Operation
Python Program to Measure the Elapsed Time in Python
Python Set isdisjoint()
How to Find an Element in a List with Java