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:
reverse()
methodreversed()
methodreverse()
methodThe 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:
list.reverse()
This method takes no parameters.
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)
Breakfast_items
.reverse()
method on the list.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)
Breakfast_items
.reversed()
methodThe 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.
reversed(list)
This method has only one parameter of the type list.
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)))
Breakfast_items
.reversed()
method on the list and print the output.Free Resources