How to Reverse a List in Python [8 Methods]

In this Python tutorial, we will learn how to reverse a Python list using different approaches or methods with examples.

There are several ways to reverse a list in Python, which are shown below:

  • Using the reverse() method
  • Using the slicing operator
  • Using a loop
  • Using the reversed() built-in function
  • Using a while loop to swap the elements of the list
  • Using recursion
  • Using the join() method and a list comprehension
  • Using the zip() function and the unpacking operator *

How to reverse a list in Python

There are many different methods to reverse a list in Python. By knowing different methods to reverse a list, programmers can choose the most suitable method for their specific use case and optimize their code for performance and readability.

Method-1: Reverse a list in Python using the reverse() method

This method uses the reverse() method of Python lists to reverse the order of elements in place.

# This code initializes a list of integers
list1 = [12, 14, 56, 24, 25, 52, 54]

# The reverse() method is called on the list1 object to reverse its elements in place
list1.reverse()

# The modified list1 is then printed to the console
print(list1)

The above code begins by creating a list of integers called list1. This list contains seven elements: 12, 14, 56, 24, 25, 52, and 54.

  • Next, the reverse() method is called on list1. This is a built-in method in Python that can be called on any list object, and it reverses the order of the elements in the list in place.
  • After the reverse() method is called, the modified list1 is printed to the console using the print() function.
Reverse a list in python with reverse function
Reversed list

Read: Linked Lists in Python

Method-2: Reverse a list in Python using the slicing operator

This method creates a new list that contains a slice of the original list starting from the last element and ending at the first element, with a step of -1 to reverse the order.

# create a list of integers
list1=[44, 75, 24, 78, 24, 84, 24]  
# print the original list
print('Original List', list1)      

# create a new list by reversing the original list using slicing
new_list=list1[::-1]              

# print the reversed list
 
print('Reversed List', new_list)   

The above code creates a list of integers list1 and then reverses the order of the elements in the list to create a new list new_list.

  • To reverse the order of the elements in list1, the code uses a slice notation with a step value of -1 to create a new list new_list with the elements in reverse order.
  • The slice notation is [::-1], which means to start at the end of the list (-1), and move backward (-1 step), until the beginning of the list (which is not specified, so the default is the start of the list).
  • Finally, the print() function is used again to output a string “Reversed List” and the contents of the new list new_list.
Output: Original List [44, 75, 24, 78, 24, 84, 24]
Reversed List [24, 84, 24, 78, 24, 75, 44]

Method-3: Reverse a list in Python using a loop

This method creates a new empty list and then iterates over the original list in reverse order using a for loop and appends each element to the new list.

# create a list of integers
original_list=[71, 36, 51, 75, 82, 78, 40]  


# print the original list
print('Original List:', original_list)   

# create an empty list for the reversed list  
reversed_list=[]  

# iterate over the elements in the original list                         
for element in original_list:               
# add each element to the front of the reversed list
    reversed_list= [element] + reversed_list 

# print the reversed list
print('Reversed List:', reversed_list)      

The code starts by creating a list of integers called original_list and prints it using the print() function.

  • Then, an empty list called reversed_list is created to store the reversed list of integers.
  • Next, a for loop is used to iterate over each element in original_list. For each element, the code creates a new list by concatenating the current element with the reversed_list using the + operator. Specifically, the current element is added to the front of reversed_list by placing it before the reversed_list in the concatenation expression.
  • Finally, the reversed list is printed using the print() function.
Output: Original List: [71, 36, 51, 75, 82, 78, 40]
Reversed List: [40, 78, 82, 75, 51, 36, 71]

Read: Python Extend Vs Append

READ:  Fibonacci series in Python [Complete program with 13 different examples]

Method-4: Reverse a list in Python using the reversed() built-in function

This method uses the reversed() built-in function to create a reverse iterator for the list, which can be converted to a list using the list() constructor.

# create a list of integers
list1= [23, 54, 76, 82, 40, 45] 

# iterate over the elements of the reversed list        
for element in reversed(list1): 
# print each element        
    print(element)                     

The above code creates a list of integers called list1.

  • Then, the for loop is used to iterate over the elements of the reversed list1. The reversed() function is called to return an iterator that iterates over the elements of list1 in reverse order.
  • During each iteration of the for loop, the current element of the reversed list is assigned to the variable element.
  • Finally, the print() function is called to print the current element to the console.
Output: 45
40
82
76
54
23

Read: Python merge two lists without duplicates

Method-5: Reverse a list in Python using a while loop to swap the elements of the list

This method uses a while loop to swap the first and last elements of the list iteratively until the entire list is reversed.

# create a list of integers
my_list = [12, 21, 31, 4, 5]           
start, end = 0, len(my_list) - 1       # initialize variables for the start and end of the list
# iterate through the list while the start index is less than the end index
while start < end:
  # swap the values at the start and end indices                     
    my_list[start], my_list[end] = my_list[end], my_list[start]
    # move the start index one position to the right    
    start += 1
    # move the end index one position to the left                         
    end -= 1   
    # print the reversed list                    
print(my_list)                         

The above code starts by defining a list of integers called my_list.

  • Next, the start variable is initialized to 0 and the end variable is initialized to len(my_list) – 1. This sets the start variable to the index of the first element in my_list, and the end variable to the index of the last element in my_list.
  • The while loop is used to iterate through the list while the start index is less than the end index. This loop will continue swapping elements until it reaches the middle of the list.
  • During each iteration of the loop, the values at the start and end indices of my_list are swapped using tuple unpacking. This swaps the first and last elements of the list, then the second and second-to-last elements, and so on, until the entire list has been reversed.
  • Finally, the print() function is used to print the reversed list to the console.
Output: [5, 4, 31, 21, 12]

Read: Concatenate multiple lists in Python

READ:  Python dictionary comprehension [7 methods]

Method-6: Reverse a list in Python using recursion

This method uses a recursive function to reverse the list. The function checks if the list has zero or one element. If so, the function returns the list unchanged.

  • Otherwise, it recursively calls itself with a slice of the list that excludes the last element, and then concatenates the last element to the result of the recursive call. This continues until the entire list is reversed.
# create a list of integers
list1 = [43, 56, 23, 75, 92, 34, 45]
# print the original list    
print('Original list:', list1)          

def rev(lst):# define a function called "rev" that takes a list as its argument
# base case: if the length of the list is zero, return an empty list
    if len(lst) == 0:                  
        return []
    return [lst[-1]] + rev(lst[:-1])   
# print the reversed list by calling the "rev" function
print('Reversed list:', rev(list1))     

The above code starts by defining a list of integers called list1. The print() function is then used to print the original list to the console.

  • The rev() function is defined to take a list as its argument. It contains two cases – the base case and the recursive case.
  • In the base case, if the length of the list is zero, an empty list is returned.
  • In the recursive case, the function returns a new list consisting of the last element of the original list and the result of calling the rev() function with all but the last element of the original list.
  • The recursive case allows the function to gradually reverse the list. The rev() function is called repeatedly with the original list as its argument, with each call removing the last element of the list until the list is empty.
  • Finally, the print() function is used to print the reversed list to the console by calling the rev() function with the original list as an argument.
Output: Original list: [43, 56, 23, 75, 92, 34, 45]
Reversed list: [45, 34, 92, 75, 23, 56, 43]

Read: How to add string to list Python

READ:  How to Create String with Single Quotes in Python

Method-7: Reverse a list in Python using the join() method and a list comprehension

This method converts each element of the list to a string, joins the strings in reverse order, and then converts the resulting string back to a list of integers.

# define the original list
my_list = [4, 5, 2, 7, 9, 3, 1]  
# convert each item to a string, reverse the order, and store in a new list
reversed_list = [str(item) for item in my_list][::-1]  
  # join the string elements of the list into a single string
reversed_str = "".join(reversed_list)
# convert each character in the string to an integer and store in a new list
reversed_list = [int(char) for char in reversed_str]
# print the reversed list  
print(reversed_list)  

The above code defines a list of integers as my_list.

  • Next, the reversed_list variable is created by using a list comprehension to convert each integer in my_list to a string, then reversing the order of the resulting list using slicing ([::-1]).
  • The reversed_str variable is created by joining the elements of reversed_list together into a single string using the join() method with an empty string ” “ as the separator.
  • Finally, a new list of integers called reversed_list is created using another list comprehension that converts each character in the reversed_str string back to an integer.
Output: [1, 3, 9, 7, 2, 5, 4]

Read: How to insert item at end of Python list

Method-8: Reverse a list in Python using the zip() function and the unpacking operator *

This method uses the zip() function to create a tuple from the reversed list and then unpacks the tuple using the unpacking operator * to create a new list.

# Create a list of integers
my_list = [1, 2, 3, 4, 5]

# Reverse the list using the reversed() function and the zip() function
# The reversed() function returns an iterator that generates the items of the input sequence in reverse order
reversed_list = list(zip(*[reversed(my_list)]))

# Print the reversed list
print(reversed_list)

The above code reverses a list of integers using the reversed() function, creates a tuple for each element using the zip() function, and then converts the resulting iterator into a list.

  • The final output is a list of tuples, with each tuple containing a single integer from the original list, in reverse order.
Output: [(5,), (4,), (3,), (2,), (1,)]

Conclusion

In this tutorial, we have covered 8 different methods to reverse a list in Python with the help of examples.

  • Using the reverse() method
  • Using the slicing operator
  • Using a loop
  • Using the reversed() built-in function
  • Using a while loop to swap the elements of the list
  • Using recursion
  • Using the join() method and a list comprehension
  • Using the zip() function and the unpacking operator *

You may also like: