In this post you will see three different ways to Reverse a List in Python without the use of any third-party libraries.
- Reverse a list Using list.reverse() method
- Reverse a list Using the “[::-1]” list slicing trick to create a reversed copy
- Reverse a List by Creating a reverse iterator with the reversed() built-in function
Examples:- Input : Mylist = [1,2,3,4,5,6,7,8] Output :New_List = [8,7,6,5,4,3,2,1,]
Method #1: Reverse a list in Python Using list.reverse() method
- Each list of Python has a built-in reverse () method that you can call the reverse contents of the list object to in-place.Reversal of the list in-place means that the new list has not been create and copying the existing elements in the reverse order. Instead, it directly modifies the original list object.
- list.reverse() Reverses the list in-place
- list.reverse() Fast, doesn’t take up extra memory
- list.reverse() Modifies the original list
My_list = [1, 2, 3, 4, 5,6,7,8] My_list.reverse() print(My_list)
Output:-
[8, 7, 6, 5, 4, 3, 2, 1]
Method #2: Reverse a list Using the “[::-1]” Slicing Trick to Reverse a Python List
- “[::-1]” Slicing Creates a reversed copy of the list
- “[::-1]” Slicing Takes up memory but doesn’t modify the original
My_list = [1, 2, 3, 4, 5,6,7,8] New_List=My_list[::-1] print(New_List)
Output:-
[8, 7, 6, 5, 4, 3, 2, 1]
Method #3: Reverse a List by Creating a reverse iterator with the reversed() built-in function
- reversed() Returns an iterator that returns elements in reverse order
- reversed() Doesn’t modify the original
- reversed() Might need to be converted into a list object again
My_list = [1, 2, 3, 4, 5,6,7,8] New_List=list(reversed(My_list)) print(New_List)
Output:-
[8, 7, 6, 5, 4, 3, 2, 1]