Register Login

Python: Reversing a list

Updated May 04, 2020

While programming in Python, you will come across lists. The elements of the list may or may not be sorted according to a particular order. For example, you may have a list of employee or student names that are sorted alphabetically. But what if you want to sort the elements in reverse alphabetical order?

There are many ways to reverse a list in Python, which we will discuss in this article along with examples to explain each of them.

In python, there are three different ways to reverse the list.

  1. Using reverse() method
  2. Using Slice operator
  3. Using reversed() method
  4. Using numpy.flip
  5. Custom Function

Python: Reversing a list

Method 1: Using reverse() Method

This is a built-in method available in python. This method reverses the given object in the list. It does not take any parameter.
The reverse() method does not return any value. After reversing the elements, it simply updates the list.

Example:

# Program for Reversing a List

# Initializing our List
My_List= [1,2,3,4,5]
print("Before Reversing :", My_List)

# Reversing using the reverse() method
My_List.reverse()
print("After Reversing :", My_List)

Output:

Before Reversing : [1, 2, 3, 4, 5]
After Reversing : [5, 4, 3, 2, 1]

Execution Time (Seconds):  0.0009989738464355469

Explanation:
In this example, we first initialized our list ‘My_List’ then printed the list before reversing. In the next line, we used the reverse() method to reverse the list.

The reverse() method neither takes any parameter nor it returns any value in this case. After reversing the list we printed our list i.e ‘My_List’. Based on the output we can see that the order of the elements has been reversed. Earlier it was [1, 2, 3, 4, 5], and after reversal it is [5, 4, 3, 2, 1].

Method 2: Using the "slice" Operator

The slice operator is used to slice a given sequence such as a list, string, tuple, etc. This technique does not reverse the elements in-place. This means that a copy of the list is made and the slicing is performed there. This process is called creating a shallow copy. This requires more space to hold the elements.

But in case the elements of the list are mutable, any modification in the original list will be reflected in the shallow copy.

This process is very fast and easy to apply. The slicing syntax is [start:stop:step]. For reversing elements, we use the code [::-1], which means that elements will be printed from the back, denoted by -1. The start and stop parameters are not given.       

Example:

# Program for Reversing a List

# Initializing our List
My_List= [1,2,3,4,5]
print("Before Reversing :", My_List)

# Reversing using the slice operator
Reversed_List = My_List[ : : -1]
print("After Reversing :", Reversed_List)

Output:

Before Reversing : [1, 2, 3, 4, 5]
After Reversing : [5, 4, 3, 2, 1]

Execution Time (Seconds):  0.0009968280792236328

Explanation:
In this example, we are used the slice operator to return the reversed elements of the list. Slice operator is denoted by two square brackets. And this operator returns the sliced part of the sequence. Negative indexing in slice operator means execution will start from the end of the list.
After slicing our list we stored it in the variable ‘Reversed_List’ and later printed it.

Method 3: Using reversed() Method

If we want to access the elements of reversed element individually we can use this method. This is a built-in function which returns an iterator that accesses the sequence in reverse order.

In the reversed() method, the original list is not modified. A shallow copy of the list is also not created. Instead, a reverse iterator is used for iterating over the elements of the list and printing them out one by one.

Example:

# Program for Reversing a List

# Initializing our List
My_List= [1,2,3,4,5]
print("Before Reversing :", My_List)

# Reversing using reversed() method
for i in reversed(My_List):
    print(i)

Output:

Before Reversing : [1, 2, 3, 4, 5]
After reversing :
5
4
3
2
1

Execution Time (Seconds):  0.0020236968994140625

Explanation:
In this example, we used the reversed method to print the item of the list individually in reverse order. As per the output, you can see that the elements are printed reverse, starting from 5 till 1. The original list of elements is not changed here.

Method 4: Using numpy.flip

The numpy.flip() method is used for reversing the order of array elements along the specified axis.

The syntax is:

numpy.flip(array, axis)

Here, the array is the list of elements that have to be reversed. The axis parameter is an integer value along which the reversal is performed. This method preserves the shape of the given array.

Example:

# Program for Reversing a List

# Import numpy
import numpy as np
array = [0, 10, 20, 40]

# Reverse list using numpy
print("Orignal List: ",array)
print("Reverse List: ",list(np.flip(array)))

Output:

Orignal List:  [0, 10, 20, 40]
Reverse List:  [40, 20, 10, 0]

Execution Time ( Seconds ):  0.540412425994873

Explanation:
In this example, the np.flip() method is used for reversing array elements. The elements stored in the variable array, are passed to the method. No axis parameter is passed to the method here. The resultant output shows that the order of the elements has been reversed.

Method 5: Custom Function

Example:

def reverse(array):
    n = array
    first = 0
    last = len(array) - 1
    while first < last:
        holder = n[first]
        n[first] = n[last]
        n[last] = holder
        first += 1
        last -= 1
    return n

list1 = [-1 ,1, 2, 3, 4, 5, 6]
print('Input List: ',list1)
print('Output List: ',reverse(list1))

Output:
Input List:  [-1, 1, 2, 3, 4, 5, 6]
Output List:  [6, 5, 4, 3, 2, 1, -1]

Execution Time ( Seconds ):  0.0009639263153076172

Explanation:
In this example, a custom function called reverse is defined for reversing the order of elements. The method takes a parameter called array. 0 is assigned to a variable called first denoting the first element of the list. The array given by the user is stored in a variable called n. The length of the array is stored in the last variable.

A while loop runs until the value of the first variable is less than the last variable. The rest of the code prints out the elements in a reversed order.

Conclusion:

If you want to reverse a list in-place and do not want to create a shallow copy, the list.reverse() method is the best choice. But in case the original list of elements cannot be modified, and you need a shallow copy - the slicing technique and reversed method is the best fit.

The custom function and the numpy.flip() method are both fast approaches to reversing elements of a list.


×