In recent times, Python is more widely used by many developers around the world, due to the availability of lots of libraries and flexible options available in python. One can choose an approach depending on the time and space complexity or easy-to-implement technique from the multiple techniques available to implement a single problem in python. Data structures in python are quite easy to understand and implement with built-in functions. In this article, let's get deep dive into the various ways to reverse a list data structure in Python.
What is a list in python?
Basically, a list is one of the data types in python to store a sequence of multiple data types in a single item. Lists are ordered which means elements are stored in a particular order. Lists are mutable which means we can access and modify the list elements and it also allows duplicate values. List items are enclosed in square brackets and separated by commas. We can create a new list by using the list() constructor.
If you want to learn how to print a list in python, check our article.
For example:
new_list = list('a', 'b', 'c') print(new_list)
Output
['a' , 'b' , 'c']
If we try to check the type of the list using type(list_name), it will return <class 'list'>
How list differs from an array?
Array size is fixed but the list can expand dynamically. In arrays, only elements of the same data type can be stored but the list can store multiple data types. In python, a list is an in-built data type so no need to import any module to use lists. But the array is not an in-built module in python so it needs to be imported separately to use in the program. You can learn more differences between array and list in our previous article.
How does list indexing work in python?
The list can be accessed and modified using indexing. The first element in the list will have an index of 0, and the following elements will have the index value in the increasing order as 1,2,3, etc., till the length of the list minus 1 index (i.e., the Last element). We can also access the elements by negative indexing which starts from the last index with -1 and decreases gradually from there till the first element. Let us understand the indexing more clearly with the following image.
How to reverse a list in Python?
There are various built-in functions available to reverse a list in python. But choosing which one to use for the specific problem is confusing. So let's look in detail at some of the ways to reverse the list in python. And after getting insights about the multiple ways, you can pick the one which would fit your requirements to reverse the list.
1) Using reverse() method
There is an in-built method known as reverse() in python that can reverse the list by changing elements in place of the original list. This method can be used in situations where memory efficiency is required. Since no extra space is required for this method, the original list itself is reversed. This method is used for reversing large lists.
For example:
original_list = [1,2,3,4,5] print("List before reverse : ",original_list) original_list.reverse() print("List after reverse : ",original_list)
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : [5, 4, 3, 2, 1]
2) Using reversed() method
This is a built-in function to reverse the list elements without creating a copy of the list or modifying the original list. It creates an iterator and stores the elements. So if we try to store the reversed list in a new list it will print the iterator object and not as a list.
For example:
original_list = [1, 2, 3, 4, 5] print("List before reverse : ",original_list) reversed_list = reversed(original_list) print("List after reverse : ", reversed_list)
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : object at 0x7f61b67ff0407>
So, to get the output as a list, we have to pass the iterator in the list method. This reversed() method can be used in places when we require a list as an iterator object or where we don't want to modify the original list.
For example:
original_list = [1,2,3,4,5] print("List before reverse : ",original_list) reversed_list = reversed(original_list) print("List after reverse : ", list(reversed_list))
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : [5, 4, 3, 2, 1]
3) Using for loop
Another way to reverse the python list without the use of any built-in methods is using loops. Create an empty list to copy the reversed elements. In the for loop, add the iterator as a list element at the beginning with the new list elements. So in that way, the list elements will be reversed. This approach can be used when you don't want to use in-built methods and want to build logic by yourself.
For example:
original_list = [1, 2, 3, 4, 5] print("List before reverse : ",original_list) reversed_list = [] for value in original_list: reversed_list = [value] + reversed_list print("List after reverse : ", reversed_list)
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : [5, 4, 3, 2, 1]
4) Using List Comprehension
In list comprehension, we can access data and perform operations using the existing list. The main idea is to reduce the code with short syntax. In our example, we can access the elements from the last index and print the elements until the starting element is reached.
For example:
original_list = [1, 2, 3, 4, 5] print("List before reverse : ",original_list) reversed_list = [] for value in original_list: reversed_list = [value] + reversed_list print("List after reverse : ", reversed_list)
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : [5, 4, 3, 2, 1]
5) Using slicing operation
Slicing is an operation performed in a list to access the list elements from a starting index to an ending index. This slicing operation can be used to reverse the list in python.
The syntax to slice the elements is List_name[start:stop:step]. So we are supposed to mention the starting and ending index. All these parameters or any of them are optional. Start indicates the starting index, stop indicates the ending index plus 1 value, and step means the number of elements we want to skip. Step value 1 means it won't skip any elements and value 2 skips one element 3 means two elements and so on. The step value cannot be zero.
For example:
original_list = [1, 2, 3, 4, 5] print("List before reverse : ",original_list) print("List after reverse : ", original_list[::-1])
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : [5, 4, 3, 2, 1]
6) Using insert() method
Another way to reverse the list using a built-in function is by using the insert() method. The insert() method is used to add elements to the list at a specific index. It takes two arguments, the first parameter is the index value in which the element has to be inserted and the next parameter is the element that is to be inserted into the list. Create a for loop and add the elements from start to the last one by one to the beginning of the list, so that we can get an output list in reverse order.
For example:
original_list = [1, 2, 3, 4, 5] print("List before reverse : ",original_list) reversed_list = [] for value in original_list: reversed_list.insert(0,value) print("List after reverse : ", reversed_list )
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : [5, 4, 3, 2, 1]
7) Using recursion
We can reverse the list by using recursion without the use of any built-in functions. Recursion means calling the function itself again and again. We can call start calling the function again and again until a single element is left and then start printing the list in the reverse order.
For example:
def list_reverse(original_list ): if(len(original_list) == 0): return original_list else: return list_reverse(original_list [1: ])+original_list[0] original_list = [1, 2, 3, 4, 5] print("List before reverse : ",original_list) print("List after reverse : ", list_reverse(original_list))
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : [5, 4, 3, 2, 1]
8) Using the slice function
The function of the Slice method is almost similar to the slicing operator. Here we have to create a separate slice object for the slice function. The slice object is created to reuse it across different values. The slice object takes the following parameters, slice[start:stop: step]. The main advantage of using this slice function is that we can give custom slices that can be reused in our programs.
For example:
original_list = [1, 2, 3, 4, 5] slice_object = slice(None, None, -1) list_reverse = original_list[slice_object] print("List before reverse : ",original_list) print("List after reverse : ", list_reverse)
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : [5, 4, 3, 2, 1]
9) Using append() and pop() methods
One more way to reverse the list in python is by using two built-in functions append() and pop(). This works by popping the last element from the original list and appending it to the new list. An important note in these two methods is that the pop method always gets the element in the last index and the append method always adds the element to the beginning of the list.
For example:
original_list = [1, 2, 3, 4, 5] print("List before reverse : ",original_list) list_reverse = [] for value in range(len(original_list)): list_reverse.append(original_list.pop()) print("List after reverse : ", list_reverse)
Output:
List before reverse : [1, 2, 3, 4, 5] List after reverse : [5, 4, 3, 2, 1]
Conclusion
Depending on your requirements, you can choose one of the above-mentioned ways of reversing lists in python. Since each approach is different, it completely depends on your problem statement whether you want to reverse the list and store it as a separate list, you need to reverse elements in place, or you need to customize your reversing, or you don't want to use in-built function and build logic on your own, and so on.