The Wayback Machine - https://web.archive.org/web/20240731015734/https://www.geeksforgeeks.org/python-reversing-list/
Open In App

Reversing a List in Python

Last Updated : 20 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Python provides us with various ways of reversing a list. We will go through some of the many techniques on how a list in Python can be reversed.

Example: 

Input: list = [4, 5, 6, 7, 8, 9]
Output: [9, 8, 7, 6, 5, 4] 
Explanation: The list we are having in the output is reversed to the list we have in the input.

Reversing a List in Python

Below are the approaches that we will cover in this article:

1. Reverse List Using Slicing Technique

In this technique, a copy of the list is made, and the list is not sorted in place. Creating a copy requires more space to hold all the existing elements. This exhausts more memory. Here we are using the slicing technique to reverse our list in Python.

Python
# Reversing a list using slicing technique
def Reverse(lst):
   new_lst = lst[::-1]
   return new_lst


lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))

Output
[15, 14, 13, 12, 11, 10]




Time complexity: O(n) 
Auxiliary space: O(n)

2. Reverse List by Swapping Present and Last Numbers at a Time

Here is the approach:

If the arr[], size if the length of the array is 1, then return arr. elif length of the array is 2, swap the first and last number and return arr. otherwise, initialize i=0. Loop for i in size//2 then swap the first present and last present numbers if the first and next numbers indexes are not same, then swap next and last of next numbers then increment i+=2, and after looping return arr.

Python
# Python program to reverse an array
def list_reverse(arr, size):
    i = 0
    while i < size // 2:
        # swap elements from the start with elements from the end iteratively
        arr[i], arr[size - i - 1] = arr[size - i - 1], arr[i]
        i += 1
    return arr


arr = [1, 2, 3, 4, 5]
size = 5
print('Original list: ', arr)
print("Reversed list: ", list_reverse(arr, size))

# This contributed by Sushrut Thakur

Output
Original list:  [1, 2, 3, 4, 5]
Reversed list:  [5, 4, 3, 2, 1]



Time Complexity: O(n), where n is the length of the given array.
Auxiliary Space: O(1)

3. Reverse List Using the Reversed() and Reverse() Built-In Function

Using reversed() we can reverse the list and a list_reverseiterator object is created, from which we can create a list using list() type casting. Or, we can also use the list reverse() function to reverse list in place.

Python
lst = [10, 11, 12, 13, 14, 15]
lst.reverse()
print("Using reverse() ", lst)

print("Using reversed() ", list(reversed(lst)))

Output
Using reverse()  [15, 14, 13, 12, 11, 10]
Using reversed()  [10, 11, 12, 13, 14, 15]



Time complexity: O(n), where n is the length of the list lst.
Auxiliary space: O(1) since it modifies the original list in place and does not create a new list.

4. Reverse a List Using a Two-Pointer Approach

In this method, we will declare two pointers(basically the start index and the end index, let ‘left’ and ‘right’). While scanning the list, in each iteration we will swap the elements at index ‘left’ and ‘right’.

The ‘left’ pointer will move forward and the ‘right’ pointer will move backward. We will continue the process till ‘first’ < ‘last’. This will work for both an even number of elements as well an odd number of elements.

Python
# Reversing a list using two-pointer approach
def reverse_list(arr):
    left = 0
    right = len(arr)-1
    while (left < right):
        # Swap
        temp = arr[left]
        arr[left] = arr[right]
        arr[right] = temp
        left += 1
        right -= 1

    return arr

arr = [1, 2, 3, 4, 5, 6, 7]
print(reverse_list(arr))

Output
[7, 6, 5, 4, 3, 2, 1]



Time Complexity: O(N)
Auxiliary Space: O(1)

5. Reverse a List Using the insert() Function

In this method, we neither reverse a list in place (modify the original list) nor create any copy of the list. Instead, we keep inserting items at the 0th index of the list, this will automatically reverse the list.

Python
# input list
lst = [10, 11, 12, 13, 14, 15]
# the above input can also be given as
# lst=list(map(int,input().split()))
l = []  # empty list

# iterate to reverse the list
for i in lst:
    # reversing the list
    l.insert(0, i)
# printing result
print(l)

Output
[15, 14, 13, 12, 11, 10]



Time complexity: O(n)
Auxiliary Space: O(n), where n is the length of the list.

6. Reverse a List Using List Comprehension

In this technique, the list is not sorted in place. A copy of the original array is not required. We use list comprehension to reverse the array and return the list.

We find the length of the array and then iterate over it using the range. Now, to replace the last element with the first, we subtract the length of the original list from the index of the iterator.

Python
original_list = [10, 11, 12, 13, 14, 15]
new_list = [original_list[len(original_list) - i]
            for i in range(1, len(original_list)+1)]
print(new_list)

Output
[15, 14, 13, 12, 11, 10]



Time complexity: O(n), where n is the length of the original_list.
Auxiliary space: O(n),

7. Reverse a List Using Numpy

Here we are going to use numpy package:

Initialize the input list my_listConvert my_list to a 1D numpy array using np.array(my_list)Reverse the order of the array using my_array[::-1]Convert the reversed numpy array back to a list using .tolist()

Print the reversed list

Python
import numpy as np

# Input list
my_list = [4, 5, 6, 7, 8, 9]

# Convert the list to a 1D numpy array
my_array = np.array(my_list)

# Reverse the order of the array
reversed_array = my_array[::-1]

# Convert the reversed array to a list
reversed_list = reversed_array.tolist()

# Print the reversed list
print(reversed_list)

Output:

[9, 8, 7, 6, 5, 4]

Time complexity: O(n) 
Auxiliary space: O(n)

We have discussed many ways of reversing a list in Python. We have also mentioned their time complexities and Auxiiary space to give you right idea about their processing speed.

Hope this article helped you to understand ways on “how to reverse a python list?” and you will easily reverse a list in Python.

Reversing a List in Python – FAQs

How do you reverse an ordered list in Python?

To reverse an ordered list in Python, you can use the reverse() method or slicing. Here are the methods:

  • Using reverse() method:
  • Using slicing:
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list) # Output: [5, 4, 3, 2, 1]
my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list) # Output: [5, 4, 3, 2, 1]

Why does list.reverse() return None?

The reverse() method in Python modifies the original list in place and does not return a new list. It returns None to indicate that it has successfully reversed the list.

Which is the correct method to reverse a list?

Both methods (reverse() method and slicing) are correct ways to reverse a list in Python. The choice between them depends on whether you want to modify the original list (reverse() method) or create a new reversed list ([::-1] slicing).

How to reverse a list in Python with slicing?

As mentioned earlier, you can reverse a list using slicing in Python:

my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list) # Output: [5, 4, 3, 2, 1]

How to reverse a list in Python without a reverse() function?

If you want to reverse a list without using the reverse() method, you can achieve it using slicing:

my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list) # Output: [5, 4, 3, 2, 1]


Previous Article
Next Article

Similar Reads

Python | Reversing a Tuple
As we know that in Python, tuples are immutable, thus it cannot be changed or altered. This provides us with limited ways of reversing a tuple, unlike a list. We will go through few techniques on how a tuple in python can be reversed. Examples: Input : tuples = ('z','a','d','f','g','e','e','k') Output : ('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z') Inpu
3 min read
Mahotas - Reversing Haar Transform
In this article we will see how we can reverse image haar transform in mahotas. The haar wavelet is a sequence of rescaled "square-shaped" functions which together form a wavelet family or basis. Wavelet analysis is similar to Fourier analysis in that it allows a target function over an interval to be represented in terms of an orthonormal basis. T
2 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Python | Remove all values from a list present in other list
Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which need to be get ridden from the original list. Let's discuss various ways How to remove the elements of a list from another list in Python. Illustration: Input: List one
10 min read
Python | Sort list according to other list order
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
5 min read
Python | Ways to Convert a 3D list into a 2D list
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development. Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source. Below are some w
3 min read
Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read
Practice Tags :
three90RightbarBannerImg