Python List reverse()
The reverse()
method reverses the order of elements in a list in place, meaning it modifies the original list rather than creating a new list.
Syntax
list.reverse()
Parameter
The reverse()
method doesn’t take any arguments
Return Value
The reverse()
method doesn’t return any value i.e. returns None
. It modifies the original list.
Example: Reverse a list of numbers
my_list = [5, 15, 10, 20]
my_list.reverse()
print(my_list) # Output: [20, 10, 15, 5]
Reverse a list without modifying the original list
If you want to create a reversed version of a list without modifying the original list, you can use slicing.
For example:
my_list = [5, 15, 10, 20]
reversed_list = my_list[::-1]
print(reversed_list) # Output: [20, 10, 15, 5]
print(my_list) # Output: [5, 15, 10, 20]
The syntax of the slicing is:
sequence[start:stop:step]
start
: (Optional) The index where the slice begins (inclusive).
stop
: (Optional) The index where the slice ends (exclusive).
step
: (Optional) The step size or interval between indexes.
In the above code example, start
and stop
are omitted, so the entire list is considered.
step=-1
means traverse the list in reverse order.
Reverse a list using the reversed() function
If you only want to access the elements of a list in reverse order without changing the original list, you can use the reversed()
function.
my_list = [5, 15, 10, 20]
# Create a reverse iterator object
rev_iterator_obj = reversed(my_list)
# Convert the reverse iterator object to list
reversed_list = list(rev_iterator_obj)
print(reversed_list) # Output: [20, 10, 15, 5]
# Original list in unchanged
print(my_list) # [5, 15, 10, 20]
The reversed()
function returns a reverse iterator object that allows you to access the elements of the original list in reverse order without modifying the list itself. If needed, you can convert the reverse iterator into a list using the list()
constructor.