Python list.reverse() function


The list.reverse() method in Python is used to reverse the order of the elements in a list in place. This means that the original list is modified, and no new list is created.

Syntax

list.reverse()

Return Value

  • The method does not return a value (None is returned implicitly) and modifies the original list.

Example Usage

  1. Reversing a List:

    my_list = [1, 2, 3, 4, 5] my_list.reverse() # Reverses the order of the list print(my_list) # Output: [5, 4, 3, 2, 1]
  2. Reversing a List of Strings: The reverse() method works with any data type within the list:

    fruits = ['apple', 'banana', 'cherry'] fruits.reverse() # Reverses the order of the fruits list print(fruits) # Output: ['cherry', 'banana', 'apple']
  3. Reversing an Already Reversed List: If you reverse a list multiple times, it will return to its original order after the second reversal:

    my_list = [1, 2, 3] my_list.reverse() # First reversal print(my_list) # Output: [3, 2, 1] my_list.reverse() # Second reversal print(my_list) # Output: [1, 2, 3]
  4. Using Reverse with an Empty List: Calling reverse() on an empty list does not raise an error:

    empty_list = [] empty_list.reverse() # Reverses an empty list print(empty_list) # Output: []
  5. Impact on References: If you have multiple references to the same list, using reverse() will affect all references:

    my_list = [1, 2, 3] another_reference = my_list my_list.reverse() # Reverses the list print(another_reference) # Output: [3, 2, 1]

Summary

  • list.reverse() is a straightforward method for reversing the elements of a list in Python.
  • It modifies the original list in place, which can be useful when you want to change the order of elements without creating a new list.
  • This method does not return a value and works with lists containing any data type.