Python Program to Reverse List

The Python program to reverse list means changing the order of the list items, where the last item (n) becomes the first, n-1 becomes the second, etc, and the first becomes the last element. In the Python programming language, there are multiple options for reversing list items. Each method has its own advantages, and this article discusses them with examples.

Within the multiple options, there are three popular techniques for reversing a list in Python: the built-in reverse(), reversed() methods, and the slicing technique. These three techniques are straightforward approaches. However, the reverse() function changes the original list, whereas the slicing and the reversed() function create a new list and preserve the original one.

The other Python list reverse options include list comprehension, for loop, while loop, recursion, and swapping techniques. A practical example for reversing the list items is to check a palindrome.

Python list reverse() method

In the Python programming language, there is a built-in list method called reverse(), which we can use to get the result. This method directly reverses the list items in the original list (in-place) without creating a new list. So, it does not require additional memory storage for a new list. However, avoid this approach to preserve the original list.

Python List reverse() Syntax

The syntax of the list reverse() function is as follows:

list_name.reverse()

As you can see from the above syntax, the built-in Python list reverse() method does not accept any arguments. It is an exclusive list function, and it cannot be applied to other data types, such as strings, tuples, and sets.

Return Value: It does not return any output value. It simply updates the existing list (list_name) with the items from the reversed list.

Python list reverse() function Examples

The following examples provide a complete understanding of the list reverse() function on strings, numbers, mixed data types, and so on.

List reverse() working with Numbers

In the following example, we declared a list of integer values (numbers). In the next line, we used the reverse() method to change the elements in an integer list. Then the print() function prints the reversed list items as the console output.

NOTE: By default, the reverse() won’t display any result. So, we must use the print() function to display the result.

a = [10, 190, 120, 180, 120, 105]
a.reverse()
print(a)
[105, 120, 180, 120, 190, 10]

The following example uses the signed and unsigned (positive and negative) numbers. The reverse() function works on a list of positive and negative numbers.

a = [9, 4, -5, 0, 22, -1, 2, 14]

a.reverse()
print(a)
[14, 2, -1, 22, 0, -5, 4, 9]

Python list reverse() function on Strings

In this example, we declared a string list (6 fruit names). Next, we used the reverse() function on it. Please refer to the List and methods articles to understand everything about them in Python.

b= ['Orange', 'Banana', 'Kiwi', 'Watermelon', 'Grape', 'Blackberry']
b.reverse()
print(b)
['Blackberry', 'Grape', 'Watermelon', 'Kiwi', 'Banana', 'Orange']

Python list reverse() function with Characters

In this example program, we use the reverse() function on a list of characters, and it will do the same for these alphabets as well.

l1 = ['a', 'b', 'c', 'd']
l1.reverse()
print(l1)
['d', 'c', 'b', 'a']

Python list reverse() function to find a palindrome number

The following example demonstrates how to use the reverse() function to check whether the list is a palindrome or not. There are multiple techniques to find a palindrome number. However, using the reverse() method to reverse the digits and comparing with the original is an efficient way.

a = [10, 20, 30, 20, 10]
b = a.copy()
b.reverse()
if a == b:
print("Palindrome")
else:
print("Not")
Palindrome

Python list reverse() function on a mixed data type

As we all know, a list can contain different data types, including integers and strings. Let me use this reverse() function on a mixed data type list of Items. If you observe the example below, it contains a string (apple and Kiwi), an integer (5), a floating-point number(10.9), and a Boolean True.

c = ['apple',  10.9, 5, 'Kiwi', True]

c.reverse()

print(c)

As you can see, it works fine on mixed data types as well and reverses them without any issue.

[True, 'Kiwi', 5, 10.9, 'apple']

Python reverse() function on the Nested List

This time, we used the reverse() method on the Nested list, and it works on the nested items as well. Here, the reverse() function considers each nested list (Sub-list) as a single element and reverses them.

d = [[171, 222], [32, 13], [14, 15], [99, 76]]
d.reverse()
print(d)
[[99, 76], [14, 15], [32, 13], [171, 222]]

How to reverse user-entered integer list items?

This program is the same as the first example, which utilizes the built-in reverse() function. However, this program allows the user to enter the list length. Next, we used a For Loop and the append function to add numbers to the list. Then, we used the built-in list reverse() method to reverse the list items.

intRevList = []

number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
intRevList.append(value)

print("Before is : ", intRevList)
intRevList.reverse()
print("After is : ", intRevList)
Python Program to Reverse List Items

Empty list

When you utilize the reverse() function on an empty list, it won’t raise any error; it simply returns the empty list as the output.

n = []
n.reverse()
print(n)
[]

Python list reverse() function Common Error

Most people try to assign the result set of the reverse() function to another variable. However, the reverse function returns None as the output. So, if you try to assign the result to a new variable, it simply returns None. For example, the first print statement returns the elements of the reversed list. On the other hand, the second print() statement returns None as the output.

a = [10, 20, 30, 40]
b = a.reverse()
print(a)
print(b)
[40, 30, 20, 10]
None

NOTE: The above-mentioned reverse() method alters the original list and replaces it with the reversed. However, there are many options we can use to reverse the list of items without changing the original list.

More Advanced techniques for Python list reverse

Apart from the earlier-mentioned reverse() and slicing techniques, Python offers more options to reverse a list of elements. This section covers all the list reverse techniques, which include using reversed(), for loop, while loop, recursion, and so on.

Python Program to Reverse List using Slicing

List slicing with the third argument as negative one is the best alternative to the traditional list reverse() method. As we all know, the slicing technique has three important things called start, stop, and step. The general syntax is

listName[start:stop:step]

If we left (omit) the first two arguments (start and stop) and set the last argument (step) as negative one (-1), it will start reading the list items from the end to the start. Here, the a[::-1] statement reads the list items in reverse order and stores them in a new list.

NOTE: It is one of the best approaches to reverse the list elements without altering the original one. However, for large datasets, it requires high memory and impacts the overall performance.

nums = [10, 20, 30, 40, 50, 60]

rev = nums[::-1]

print(rev)
[60, 50, 40, 30, 20, 10]

Reverse a Nested List using slicing

The slicing technique also works well with the nested list. The program reverses the nested list items using the slicing technique with a negative step value. Here, it considers each nested list as one element and reverses them in order.

a = [[10, 25], [50, 75], [100, 125]]
print(a[::-1])
[[100, 125], [50, 75], [10, 25]]

Python program to reverse list using the reversed() function

Python has a built-in reversed() function, which is another way to reverse the elements of a list. Unlike the Python list reverse() function, it will not modify the original list because it creates an iterator instead of a new list. So, if our priority is to reverse the elements in a list without changing the original one, use the reversed() function.

Imagine there is a large dataset. Creating a copy of the reversed list is memory-intensive and time-consuming. On the other hand, the reversed() function iterates them in reverse order.

a = [11, 25, 90, 70, 50, 60]

n = list(reversed(a))
print(n)
[60, 50, 70, 90, 25, 11]

By default, the reversed() function returns the iterator object, so we have to convert it back to a list. To demonstrate this, add the line below to the above code; it will display the iterator object as an output. Here, the list() function (list(reversed(a))) converts this iterator object to a regular list, and the print statement will return the result.

print(reversed(a))
<list_reverseiterator object at 0x00000218E9A8B940>

Generally, we can use the Python reversed() function to iterate over a list of items in reverse order without creating a copy (original or reversed). So, if we use it directly in the for loop or while loop, the reversed() function reads the list elements in reverse order without storing them in a variable.

The following example uses the next() function to read the elements in the iterator.

a = [1, 2, 3]

b = reversed(a)
print(a)
print(b)
print(next(b))
print(next(b))
print(next(b))
[1, 2, 3]
<list_reverseiterator object at 0x000001CE0719B400>
3
2
1

Using the slice() method

In the Python programming language, the slice() method is used to reverse a list. It accepts three arguments, and all we have to do is add None as the first two arguments (start and stop) and -1 as the third (step).

In the example below, we declared a string list of fruit items. Next, the slice() method is used to reverse the items in a list and create a slice object. Once this slice object is created, we can use it on multiple lists. Here, we apply it to the string list.

a = ['Apple', 'Kiwi', 'Orange', 'Banana']
b = slice(None, None, -1)
c = a[b]

print(a)
print(c)
['Apple', 'Kiwi', 'Orange', 'Banana']
['Banana', 'Orange', 'Kiwi', 'Apple']

Python list reverse using list comprehension

List comprehensions provide a flexible and easy-to-read single-line code for reversing the elements in a list. The following example uses the slicing approach within the list comprehension to reverse the elements. It builds a completely new list with reverse list elements.

a = [1, 2, 3, 4]
b = [n for n in a[::-1]]
print(b)
[4, 3, 2, 1]

This example uses a for loop and range function inside a list comprehension to iterate over the items in reverse order. Next, store each item from last to first in another variable.

Here, we use the list index position to access the items in reverse order. Since we assign them to a new empty list (b), we create a completely new list with reversed elements.

a = [1, 2, 3, 4, 5]
b = [a[n] for n in range(len(a)-1, -1, -1)]
print(b)
[5, 4, 3, 2, 1]

Using map and lambda functions

The following Python program uses the map and lambda functions to reverse the list items.

a = [10, 20, 30, 40]
r = list(map(lambda x: a[-x], range(1, len(a) + 1)))
print(r)
[40, 30, 20, 10]

Python program to reverse list items using the NumPy module

Within the NumPy module, there is a flip() method that we can use to reverse the existing order of the items.

NOTE: Use this function if you are working with NumPy array data. Otherwise, avoid this approach. Here, we need to convert the existing list to an array, reverse it, and then convert it back to a list.

import numpy as np
a = [1, 2, 8, 3, 4]
b = np.array(a)
c = np.flip(b)
d = c.tolist()
print(d)
[4, 3, 8, 2, 1]

Python Program to Reverse List items using a for loop

If we don’t want to use any built-in function to reverse the list elements, using the looping technique and a for loop is the first option. We can use the for loop to iterate over the list items in index-based or traverse them from start to end. Remember, it does not change the original list.

In the following program, we declared an integer list and an empty list. The for loop iterates the original list items from start to end. Within the loop, we assign each item to the first position and push the existing items to the last. The Code Execution follows the approach.

  • First Iteration: [25]
  • Second: [77, 25]
  • Third: [90, 77, 25]
  • Fourth: [80, 90, 77, 25]
  • Fifth: [150, 80, 90, 77, 25]
a = [25, 77, 90, 80, 150]
b = []

for i in a:
b = [i] + b

print(b)

OUTPUT

[150, 80, 90, 77, 25]

Using the for loop and the range() function

We can say it is an extension of the above slicing technique. This example code uses a for loop and the range function to iterate over list elements from last to first and append them to the new list.

Here, the for loop with the range() function helps traverse from the list’s last index position (n) to the first (0) with a step of -1 (descending). The append() function adds each item to the rev list.

a = [10, 20, 90, 40, 50]
rev = []
n = len(a) - 1
for i in range(n, -1, -1):
rev.append(a[i])

print(rev)
[50, 40, 90, 20, 10]

Using a for loop and the insert() function

We can also use the Python for loop and the list insert() function to reverse the elements. Here, we use the insert() function to load each item from the for loop iteration into the first position of the rev list. When the next iteration begins, the existing item is pushed to the next position, and the current value is inserted into the first position.

nums = [10, 20, 30, 40, 50, 60]
rev = []

for i in nums:
rev.insert(0, i)

print(rev)
[60, 50, 40, 30, 20, 10]

NOTE: We can also use the append() and pop() functions in combination inside the for loop to reverse list items.

Access List Items in reverse order

The other option is using the reversed() function inside a for loop to read or print the list items in reverse order. The following example uses the reversed() function directly inside the for loop to display the list items in reverse order.

If your goal is to access the individual list items in a reverse order, use the below-mentioned reversed() function inside the for loop.

a = [1, 2, 3]

for item in reversed(a):
print(item)
3
2
1

We can use the append() function to add or assign the reversed items to a completely new list.

a = [1, 2, 3]
b = []
for item in reversed(a):
b.append(item)

print(a)
print(b)
[1, 2, 3]
[3, 2, 1]

Python program to reverse a list using a while Loop

Apart from the for loop, we can also use the while loop to reverse the list items manually by iterating over them in reverse order. The series of examples in this gives an idea of how we can use the while loop to reverse a list.

In this program, we declared a list of numbers and an empty list to store the reversed items. Next, len(a) – 1 returns the last index item in a given list. It means initializing the counter variable to the last index position.

Here, the while loop will start iterating the list items from the last index position to the first position (i >= 0). Within the loop, the list append() function adds each element to the b list (from last to first). Since the loop starts at the last position, for each iteration, we used i -= 1 to decrement the index position by one.

a = [10, 20, 30, 40]
b = []
i = len(a) - 1

while i >= 0:
b.append(a[i])
i -= 1

print(b)
[40, 30, 20, 10]

Using append() and pop() method

This example also uses the while loop, but we used the list pop() method to reverse the items this time and append() to add those elements.

Here, the while loop iterates the list items one after the other. Next, the pop() function removes and returns the last value (number from the last index position) from the list. The append() method will add that number to a new list.

nums = [10, 20, 30, 40, 50, 60]
rev = []

while nums:
rev.append(nums.pop())

print(rev)
[60, 50, 40, 30, 20, 10]

TIP: We can also use the for loop to iterate over the list items. If we try to print the original list, it returns an empty list because on each iteration, the pop() removes the last item until the list becomes empty.

Python program to reverse list items using the swap technique

In this Python program, we are using a While loop. Inside the while loop, we performed the swapping with the help of the third variable. Here, we swap the first and the last item in a list. Next, the loop moves inwards and swap 2nd and the last but one.

Some people say it is a program to reverse list items using the two-pointer approach. I suggest referring to the Swap Two Numbers article to understand the Python logic.

a = [10, 25, 50, 75, 100]
j = len(a) - 1
i = 0

while i < j:
temp = a[i]
a[i] = a[j]
a[j] = temp
i = i + 1
j = j - 1

print(a)
[100, 75, 50, 25, 10]

The above-mentioned while loop approach works perfectly. However, we can use the swapping approach mentioned below to reverse the list items. Here, the for loop traverses to the middle of the list items and swaps the first and last item. Next, it moves to the next item to swap them.

a = [10, 25, 50, 75, 100]
j = len(a)

for i in range(j // 2):
a[i], a[j - i - 1] = a[j - i - 1], a[i]

print(a)
[100, 75, 50, 25, 10]

Python Program to Reverse List items using Functions

This List items program is the same as the above. However, we separated the logic using Functions.

def revfun(a, n):
j = n
i = 0
while i < j:
a[i], a[j] = a[j], a[i]
i = i + 1
j = j - 1


a = [10, 20, 44, 30, 40, 50]
n = len(a) - 1
revfun(a, n)
print("\nThe Result = ", a)

OUTPUT

The Result =   [50, 40, 30, 44, 20, 10]

Python Program to Reverse List Elements Using Recursion

This program reverses the List items by calling the revitem() function recursively with updated values. Here, within the if statement, the first statement swaps the first and last values. The next line calls the revitem() function with the updated values (second and last but one, and so on).

def revitem(a, i, j):
if i < j:
a[i], a[j] = a[j], a[i]
revitem(a, i + 1, j - 1)

a = [12, 13, 14, 15, 16, 27]
revitem(a, 0, len(a) - 1)
print(a)

OUTPUT

[27, 16, 15, 14, 13, 12]

A better approach to reverse the list items using recursion is shown below.

def revitem(n):
if len(n) == 0:
return []
else:
return revitem(n[1:]) + [n[0]]
# return [n[-1]] + revitem(n[:-1])

nums = [25, 77, 90, 80, 150, 60, 180]
rev = revitem(nums)
print(rev)

OUTPUT

[180, 60, 150, 80, 90, 77, 25]

Using __reversed__() function

In the Python programming language, there is a special function called __reversed__() to reverse the list items.

a = [10, 25, 50, 75, 99, 100]

n = a.__reversed__()

for i in n:
    print(i, end = " ")
100 99 75 50 25 10