1 min read
How many methods are there to reverse a list in python?
Vishal Sharma Answered question September 13, 2019
1 min read
There are three method to reverse a list in python that are given below:
- Reversing a list in-place with the
list.reverse()
method - Using the “
[::-1]
†list slicing trick to create a reversed copy - Creating a reverse iterator with the
reversed()
built-in function
Reversing a List In-Place With the list.reverse()
Method
>>> list = [,4,5,67,88,9] >>> list.reverse() >>> list [9,88,67,5,4]Using the “
[::-1]
†Slicing method to Reverse a Python List>>> list = [5,6,7,90,9] >>> list[::-1] [9,99,7,6,5]Creating a Reverse Iterator With the
reversed()
Built-In Function>>> new_list = [1,2,3,45,5] >>> print(list(reversed(new_list))) [5,45,3,2,1]
or
>>> mylist = [1, 2, 3, 4, 5] >>> for item in reversed(mylist): ... print(item) 5 4 3 2 1 >>> mylist >>> [1, 2, 3, 4, 5]
Vishal Sharma Answered question September 13, 2019