Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Reversing a List in Python

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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] 

Reversing list by swapping present and last numbers at a time:

Approach:

Input: arr[], size
1)if length of array is 1, then return arr.
2)elif length of array is 2, swap first and last number and return arr.
3)otherwise initialize i=0.
  a)Loop for i in size//2
  b)swap first present and last present numbers.
  c)if first and next numbers indexes are not same, then swap next and last of next numbers.
  d)increment i+=2.
4)after looping return arr.

Python3




#Python program to reverse an array
def list_reverse(arr,size):
 
    #if only one element present, then return the array
    if(size==1):
        return arr
     
    #if only two elements present, then swap both the numbers.
    elif(size==2):
        arr[0],arr[1],=arr[1],arr[0]
        return arr
     
    #if more than two elements presents, then swap first and last numbers.
    else:
        i=0
        while(i<size//2):
 
    #swap present and preceding numbers at time and jump to second element after swap
            arr[i],arr[size-i-1]=arr[size-i-1],arr[i]
       
    #skip if present and preceding numbers indexes are same
            if((i!=i+1 and size-i-1 != size-i-2) and (i!=size-i-2 and size-i-1!=i+1)):
                arr[i+1],arr[size-i-2]=arr[size-i-2],arr[i+1]
            i+=2
        return arr
 
arr=[1,2,3,4,5]
size=5
print('Original list: ',arr)
print("Reversed list: ",list_reverse(arr,size))
 
#This contributed by SR.Dhanush

Output

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

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

Reversing a 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 list.reverse() function to reverse list in-place.

Python3




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.

Reversing 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.

Python3




# 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)

Reversing 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.

Python3




# 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 length of list

Reversing a list using the 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.

Python3




# 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]

The time complexity of the Reverse function using slicing technique is O(N), where N is the length of the input list ‘lst’.
The auxiliary space used by the Reverse function is also O(N), where N is the length of the input list ‘lst’. 

Reversing 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 the list comprehension to reverse the array and return the list.

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

Python3




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]

The time complexity is O(n), where n is the length of the original_list.
The auxiliary space is also O(n),

Reversing a list using reduce method

In this technique, the list iterate over each element and append the element to the front of list and at last we get array in reverse order. At each iterate we convert the item in to list and concatenate the previous array with front element to current element list.

Python




from functools import reduce
 
original_list = [10, 11, 12, 13, 14, 15]
new_list = reduce(lambda a, b : [b]+[a] if type(a)==int else [b]+a , original_list)
print(new_list)

Output

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

Using append function

1. A new, empty list called reversed_lst is initialized.
2. A for loop is used to iterate over the indices of the original list in reverse order. The loop starts from the index of the last element in the list (i.e., len(lst)-1) and goes backwards to the first element (i.e., index 0). For each index, the corresponding element is appended to reversed_lst.
3. Once the loop has finished, reversed_lst contains all of the elements of the original list in reverse order, so it is returned.

Python3




def reverse_list(lst):
    reversed_lst = []
    for i in range(len(lst)-1, -1, -1):
        reversed_lst.append(lst[i])
    return reversed_lst
lst = [1, 2, 3, 4, 5]
reversed_lst = reverse_list(lst)
print(reversed_lst)  # Output: [5, 4, 3, 2, 1]

Output

[5, 4, 3, 2, 1]

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

Method: Reversing a list using a for loop and insert() function to create a new reversed list

Here are the steps to reverse a list using a for loop and insert() function to create a new reversed list:

  1. Create an empty list to store the reversed values.
  2. Use a for loop to iterate through the original list backwards.
  3. Inside the loop, use the insert() function to add each value from the original list to the beginning of the reversed list.
  4. After the loop completes, the reversed list will contain all the values from the original list in reverse order.
  5. Print the reversed list.

Python3




# Input list
my_list = [4, 5, 6, 7, 8, 9]
 
# Initialize an empty list to store reversed values
reversed_list = []
 
# Loop through the original list backwards
for i in range(len(my_list)-1, -1, -1):
    # Insert each value at the end of the reversed list
    reversed_list.append(my_list[i])
 
# Print the reversed list
print(reversed_list)

Output

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

The time complexity of this approach to reverse a list is O(n), where n is the number of elements in the list.
The auxiliary space complexity of this approach is also O(n), as we need to create a new list to store the reversed values. 

Method: Using numpy:

 Algorithm :

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

Python3




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)
#This code is contributed by Jyothi pinjala.

Output:

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

The time complexity : O(n), where n is the length of the input list. This is because we need to iterate through the entire list to convert it to a numpy array, and then again to reverse the order of the array. The tolist() function also takes O(n) time to convert the reversed array back to a list.

The auxiliary space : O(n), where n is the length of the input list. This is because we create a new numpy array of the same size as the input list. However, this array is temporary and will be garbage collected once the reversed list is created.


My Personal Notes arrow_drop_up
Last Updated : 05 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials