Python List reverse() Function
The List reverse()
method reverses the order of elements in the list in place.
The reverse()
method does not return any value: it modifies the original list.
Syntax
my_list.reverse()
reverse() Parameters
Python List reverse()
function does not take any parameters.
reverse() Return Value
Python List reverse()
function does not return any value: it updates the existing list.
Examples
Example 1: Reverse a list with reverse() method
The reverse()
method can be used with lists that contain data of any type.
For example, reverse a list of numbers:
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # Output: [5, 4, 3, 2, 1]
output
[5, 4, 3, 2, 1]
Or reverse a list of strings:
names = ['Tom', 'Anna', 'David', 'Ryan']
names.reverse()
print(names) # Output: ['Ryan', 'David', 'Anna', 'Tom']
output
['Ryan', 'David', 'Anna', 'Tom']
Example 2: Reversing a List of Mixed Data Types
The reverse()
method can reverse a list containing mixed data types too!
my_list = [1, 'Anna', 2, 'David', 3, 'Tom']
my_list.reverse()
print(my_list) # Output: ['Tom', 3, 'David', 2, 'Anna', 1]
output
['Tom', 3, 'David', 2, 'Anna', 1]
reverse() method vs reversed() built-in function
If you do not want to modify the list but access items in reverse order, you can use reversed() built-in function.
It returns the reversed iterator object, with which you can loop through the list in reverse order.
- The
reverse()
method reverses and modifies the original list. - The
reversed()
function creates a reversed list without modifying the original list.
original = [1, 2, 3, 4, 5]
original.reverse() # modify the original list
print(f'Using reverse(): {original}') # Output: [5, 4, 3, 2, 1]
# Using reversed() to create a reversed list without modifying the original (and now reversed) list
reversed_numbers = list(reversed(original))
print(f'Using reversed(): {reversed_numbers}') # Output: [1, 2, 3, 4, 5]
output
Using reverse(): [5, 4, 3, 2, 1]
Using reversed(): [1, 2, 3, 4, 5]