Python - How To Reverse a List in Python

ID : 336

viewed : 54

Tags : PythonPython List

vote vote


Python list is a collection of different objects like strings, characters, boolean and integers, etc. This article will introduce methods to reverse a list in Python, like the reverse() method, reversed() method, and the list slicing method.

Python Reverse List With the reverse() Method

Let’s take the below list as an example.

list=["cat","dog","bird","insects"] list.reverse() print(list) 

The reverse() method does not create a new list but reverses the original list items.

The output of the reverse() Method is:

['insects', 'bird', 'dog', 'cat'] 

Similarly, we can reverse the integer list.

int_list=[5,15,30,50,70] int_list.reverse() print(int_list) 


[70, 50, 30, 15, 5] 

Python Reverse List With the reversed() Function

The Python built-in function reversed() returns the iterator that reverses the given sequence. We can use the for loop to access each element in the returned iterator.

species_list=["cat","dog","bird","insects"] for i in reversed(species_list):     print(i) 


insects bird dog cat 

We can put the reversed iterator in the list() to get the result as a list.

species_list=["cat","dog","bird","insects"] list(reversed(species_list)) 


['insects', 'bird', 'dog', 'cat'] 

Reverse List With the Slicing Method in Python

We can also use the slicing method to reverse the list in Python.

The example code is:

species_list=["cat","dog","bird","insects"] print(species_list[::-1]) 


['insects', 'bird', 'dog', 'cat'] 

This method has a drawback as it produces a copy of the list and occupies more memory than the reverse() and reversed() method.

In terms of computational efficiency, the reverse() method is fastest than the reversed() and the slicing method.

  • Related HOW TO?