How to use the reverse() and reversed() methods in Python
Overview
In list reversal, the last element becomes the first element and following the same pattern, the position of all the elements is changed, and the first becomes the last. If we want to reverse our Python list, there are three main methods available for it:
- The
reverse()method - The slicing method
- The
reversed()method
The reverse() method
The list class in Python has built-in reverse() function, which when called, reverses the order of all the elements in the list. This function does not take any argument and reverses the object on which it is called upon. It modifies the given list and does not require extra memory. An axample is given below:
Syntax
list.reverse()
Parameters
This method takes no parameters.
Return value
This method reverses the given list.
Breakfast_items = ['Bread', 'Butter', 'Jam', 'Cereal','Eggs','Juice']print('List of Items:', Breakfast_items)Breakfast_items.reverse()print('Reversed List of Items:', Breakfast_items)
Explanation
- Line 1: We create a list with the name,
Breakfast_items. - Line 2: We print all the elements in the list.
- Line 4: We call the
reverse()method on the list. - Line 6: We print the updated list.
The slicing method
The slicing method works on iterables in Python and we exploit this to our advantage. However, the original list remains unchanged because a shallow copy is created in slicing. For this, more memory is required.
Breakfast_items = ['Bread', 'Butter', 'Jam', 'Cereal','Eggs','Juice']print('List of Items:', Breakfast_items)rev= Breakfast_items[::-1]print('Reversed List of Items:', rev)
Explanation
- Line 1: We create a list with the name
Breakfast_items. - Line 2: We print all the elements in the list.
- Line 4: We call the slicing method on the list.
- Line 6: We print the updated list.
The reversed() method
The reversed() function does not reverse anything but returns an object to iterate over the elements in reverse order. It modifies the list but the reversed() method gives an iterator to help traverse the given list in reversed order.
Syntax
reversed(list)
Parameters
This method has only one parameter of the type list.
Return value
This method returns an iterator, which gives access to the given sequence in the reverse order.
Breakfast_items = ['Bread', 'Butter', 'Jam', 'Cereal','Eggs','Juice']print('List of Items:', Breakfast_items)print('Reversed List of Items:',list(reversed(Breakfast_items)))
Explanation
- Line 1: We create a list with the name
Breakfast_items. - Line 2: We print the list of items.
- Line 4: We call the
reversed()method on the list and print the output.
Free Resources