Python Program to Reverse List

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 two popular techniques for reversing a list in Python: the built-in reverse() method and the slicing technique. These two techniques are straightforward approaches. However, the reverse function changes the original list, whereas the slicing creates a new list and preserves the original one.

TIP: 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.

Syntax

The syntax of the Python list reverse function is as follows:

list_name.reverse()

As you can see from the above syntax, the built-in 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.

NOTE: It does not return any output value. It simply updates the existing list with the items from the reversed list.

Python list reverse Examples

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

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.

a = [9, 4, -5, 0, 22, -1, 2, 14]
print("Original : ", a)
a.reverse()
print("New : ", a)
Original :  [9, 4, -5, 0, 22, -1, 2, 14]
New  :  [14, 2, -1, 22, 0, -5, 4, 9]

Working on Strings

In this example, we declared a string list. 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']

Working with Characters

In this Python 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 Practical Example

The following example demonstrates how to use the reverse() function to check whether the list is a palindrome or not.

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

Using reverse() on Mixed Data type List

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.

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

Using the 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.

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

Python list reverse 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.

Python Program to Reverse a List using Slicing

As we all know, the slicing technique has three important things called start, stop, and step. If we left (omit) the first two arguments 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.

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

rev = nums[::-1]

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

Reverse a Nested List

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.

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

More Advanced techniques

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

Using the reversed() function

Python has a built-in reversed() function, which is another way to reverse the elements of a list. Unlike the 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 this 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

Access List Items in reverse order

Similarly, we can use the Python 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]

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

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

Using Python list comprehension to reverse elements

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. 

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

Using a swapping 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. 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 aforementioned 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]

Using 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 have to convert the existing list to an array, flip it, and then convert 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 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 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.

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

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]

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]

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