reverse a list in python

How to Reverse a List in Python? [1st one is the best and fastest]

We programmers often need to reverse a list for various use cases, so it is crucial to know different ways to reverse a list in python, understand the pros and cons of them and choose the best one for your needs.

In the following sections, we will walk you through the 10+ different options to reverse a list in Python and time comparisons of them.

Quick Summary

If you are looking for a method to reverse a list in-place in Python then the following options should work for you. Our choice is using reverse() since it is swift and reverses a list in place.

  • The reverse() method
  • Two Pointers Approach

In case your search is for a method that creates a new list, then all the following methods work. Our recommendation is the using slice operator or slice function since they are quicker than the other ways.

  • Slice Operator
  • Slice Function
  • Reversed Method
  • Numpy’s flip Method

We suggest you, not to use the below methods in production-level code. Since they are resource-heavy approaches.

  • Recursive reverse approach
  • Reduce method
  • for loop and insert method

Fastest way to reverse a list in Python

We have profiled all the below listed 13 methods against 10 million numbers. The Following are times taken to reverse a list in milliseconds.

Please note that these times are approximate and can vary depending on machine capacity and other factors.

Fastest way:

The reverse() method is the fastest and simplest way to reverse a list in python.

MethodTime Taken in MillisecondsMemory Usage In MB
Reverse Method70
Slice Operator4876
Slice function4976
Reversed Method6676
List Comprehension42084
Numpy flip() function47876
For loop and extra array59484
Two Pointers Approach6380
Loop and pop() method7380
While loop and extra array82984
Recursive ReverseNA – Takes significant timeNA
Reduce FunctionNA – Takes significant timeNA
Loop and insert method1600

Different ways to reverse a list in python?

Method 1: With the reverse() method

You can use the list’s reverse() method to reverse the order of the elements that they appear in.

The following are a few notes about the reverse() method:

  • The reverse() method modifies the current list in place
  • The reverse() method returns None
  • Internally reverse() method is implemented using two pointers approach.
  • It takes O(N) time and does not use any extra space.
salaries = [14000, 17000, 13000, 19000, 21000]

# list's built-in reverse() method modifies the current list and returns None.
salaries.reverse()

print(salaries)
#output: [21000, 19000, 13000, 17000, 14000]

Method 2: Using the slicing operator

You can use the slicing operator to reverse a list in python.

The slicing operator takes three parameters as input. All these parameters are optional.

Syntax: [start:end:step]

  • start: slice will start from this index, by default it is 0.
  • end: slice will end at this index, by default it is the length of the list
  • step: size to increase at every iteration from start to end, by default it is 1.

If you specify a negative step number then slicing will be reversed. It takes O(N) time and creates an extra list.

salaries = [14000, 17000, 13000, 19000, 21000]

# slicing operator creates a new reversed list and returns it.
salaries = salaries[::-1]

print(salaries)
#output: [21000, 19000, 13000, 17000, 14000]

Method 3: Use reversed() method

As the name implies, reversed() method can be used to reverse a list.

  • The reversed() method takes the sequence object as input.
  • It creates a new reversed iterator and returns it.
  • It works in O(N) time.
salaries = [14000, 17000, 13000, 19000, 21000]

# reversed() builtin method creates a new reverse iterator and returns it.
salaries = list(reversed(salaries))

print(salaries)
#output: [21000, 19000, 13000, 17000, 14000]

Method 4: Two Pointers approach

In this method, we take two pointers start and end. Initially start is at the 0th index and the end is at the len(list)-1 index. We will swap elements at the start and end positions in place and repeat this process till the start is less than the end.

  • This approach does not create a new list but reverses the list in place
  • It takes N/2 iterations to complete the process, so time complexity is O(N)
salaries = [14000, 17000, 13000, 19000, 21000]

start = 0
end = int(len(salaries)) - 1

while start < end:
    
    #swapping elements at the start and end indices
    temp = salaries[start]
    salaries[start] = salaries[end]
    salaries[end] = temp
    start = start + 1
    end = end - 1

print(salaries)
#output: [21000, 19000, 13000, 17000, 14000]

Method 5: With for loop and an extra list

Alternatively, Without using inbuilt functions like reverse(), reversed() and slice operators, we could use an extra array and a for loop to invert the list in Python. We traverse the list from ending to beginning using for loop. While traversing reverse we append elements to the new list.

  • Creates a new array and does not reverse in place
  • Uses O(N) extra space and time complexity is O(N)
salaries = [14000, 17000, 13000, 19000, 21000]

new_salaries = []
index = len(salaries) - 1

# Traversing the list in reverse
for i in range(len(salaries)-1, -1, -1):

    # Appending each element to the new list
    new_salaries.append(salaries[i])

print(new_salaries)
#output: [21000, 19000, 13000, 17000, 14000]

Method 6: Using a while loop and an extra list

This approach is quite similar to Method 5 except that we have used a while loop instead of for loop in this method.

  • The following algorithm uses O(N) extra space and time complexity is O(N)
salaries = [14000, 17000, 13000, 19000, 21000]
new_salaries = []
index = len(salaries) - 1

#Iterating over the list using while loop
while index >= 0:

    #Add each element to the newly created list
    new_salaries.append(salaries[index])
    index = index -1

print(new_salaries)
#output: [21000, 19000, 13000, 17000, 14000]

Method 7: Recursive Approach

Following is a simple recursive way to reverse a list.

  • Base case: If we have only one element then we don’t need to reverse it, just can return the same.
  • Recursive case: Let’s say we have a list with 3 elements. We will take out the last element and for the list excluding the last element, will invoke the recursive method.

Notes:

  • Use this method only for learning purposes but not in production-level code bases.
  • Use this method only when the list size is small, less than 100
  • You will get RecursionError: maximum recursion depth exceeded on bigger lists
# Recursion method to reverse the elements in list
def reverse_recursive(elements):
    # to handle None lists, reverse_recursive(None)
    if elements is None:
        return None

    # to handle empty lists, reverse_recursive([])
    elif len(elements) == 0:
        return []

    # to handle list with one element, we will return as it is.
    elif len(elements) == 1:
        return [elements[0]]

    else:
        '''get last element and keep it at first place and
        repeat same procedure recursively for the list without
        last element'''

        last_element = [elements[-1]]
        remaining_list = elements[:-1]
        return  last_element + reverse_recursive(remaining_list)


salaries = [14000, 17000, 13000, 19000, 21000]
print(reverse_recursive(salaries))
#output: [21000, 19000, 13000, 17000, 14000]

Method 8: Using for comprehension

Another approach to invert a list in python is to use the for comprehension. Here we create a new list while we iterate through the list in reverse order.

  • It creates a new list and, does not reverse in place.
  • Space complexity is O(N) and Time complexity is O(N)
salaries = [14000, 17000, 13000, 19000, 21000]

#for comprehension syntax
new_salaries = [salaries[index] for index in range(len(salaries)-1, -1, -1)]

print(new_salaries)
#output: [21000, 19000, 13000, 17000, 14000]

Method 9: With for loop and insert method

In this method, we traverse the list from start to end and in each iteration, we insert the current element in the first position.

  • Space complexity is O(N) since we are using an extra array
  • Time complexity is O(N)
salaries = [14000, 17000, 13000, 19000, 21000]
new_salaries = []

#Iterate the list from the last index and insert element to new list
for i in range(0,len(salaries)):
    new_salaries.insert(0,salaries[i])

print(new_salaries)

#output: [21000, 19000, 13000, 17000, 14000]

Method 10: slice() function

The slice function is quite similar to the slice operator(:). The slice function takes three input parameters.

  • start: slice start point, by default, it will be 0. None will be treated as 0.
  • end: slice will end at this index, by default it is the length of the list. None will be treated as the length of the list.
  • step: size to increase at every iteration from start to end, by default it is 1.

When a negative step is given slice will happen in reverse order. It works in O(N) time and creates a new list.

salaries = [14000, 17000, 13000, 19000, 21000]

#using slice() function to reverse the list
print(salaries[slice(None, None, -1)])

#output: [21000, 19000, 13000, 17000, 14000]

Method 11: Using the pop() function

When you call, the pop() function on a list, it will remove and returns the last element from the list.

In this approach, we iterate the list in reverse order and call the pop() function to get the last element.

  • Extra space is required, so space complexity would be O(N)
  • Time Complexity is O(N)
  • Note that it removes the elements from the original list.
salaries = [14000, 17000, 13000, 19000, 21000]
new_salaries = []

#Loop through the list and get the last element using pop()
for i in range(len(salaries)):
    new_salaries.append(salaries.pop())

print(new_salaries)

#output: [21000, 19000, 13000, 17000, 14000]

Method 12: With numpy.flip()

NumPy’s flip takes the list as input and returns NumPy’s ndarray.

  • flip can reverse multi-dimensional arrays. For examples: Please visit NumPy’s Documentation.
  • It also takes an optional axis parameter. if you pass the axis as 0 it flips the array or list horizontally and vertically when the axis is passed as 1.
import numpy as np

salaries = [14000, 17000, 13000, 19000, 21000]

#reverse a list using numpy library method
print(list(np.flip(salaries)))

#output: [21000, 19000, 13000, 17000, 14000]

Method 13: Use the reduce() function

The final method to invert a list in python is to use the reduce() method. This method takes below three parameters.

  • Function
  • Sequence
  • Initialization

In our case, for the function parameter, we have passed a lambda function that takes two parameters x and y, and returns a list that is a result of [y] + x. For sequence, we have passed the salaries list and initialization as an empty list.

Elements from the salaries list will be passed to the lambda function one at a time from left to right as a y parameter. and for the first time initialization value, an empty list will be passed x. From next time, the last step returned list will be passed as x.

from functools import reduce

salaries = [14000, 17000, 13000, 19000, 21000]

#reduce function to invert a list
print(reduce(lambda x, y: [y] + x, salaries, []))

#output: [21000, 19000, 13000, 17000, 14000]

Frequently Asked Questions

  • Does reverse() create a new list?

    No, reverse() works in place. It won’t create a new list.

  • How do you reverse a list without an inbuilt function?

    The following options do not use inbuilt functions.

    1. Two pointers approach
    2. Using for loop and an extra list

  • How do you reverse a list without using the reverse function?

    You could use one of the following options to reverse a list without using the reverse function.

    1. Slicing operator or function
    2. Reduce() function
    3. Two Pointers approach
    4. NumPy’s flip function

  • How do you reverse a list in python without a loop?

    You can use the slicing operator.

    ratings = [1,2,3,4,5]
    print(ratings[::-1])

    You can even use reduce method in which you don’t need a loop.

  • How do you reverse a list in python while loop?

    Using a while loop you can create a reverse list with the following methods.

    1. Two Pointers approach
    2. While Loop and an extra list

  • How do you reverse a list in python with slicing?

    The following two methods use slicing to reverse a list.

    Using Slicing operator
    Using Slicing function

Leave a Comment

Your email address will not be published. Required fields are marked *