Python: Reverse a list, sub list or list of list | In place or Copy

In this article we will discuss different ways to reverse contents of a list or list of lists. We will also cover scenarios where we create a reverse copy of the list or reverse the contents of the list in place.

Suppose we have a list,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

Now first we will discuss ways to get a copy of this list with reversed contents. Then later we will discuss how to reverse the contents of this list in-place.

Get a reversed list using reversed() function

Python provides a builtin function reversed() i.e.

reversed(seq)

It accepts a sequence and returns a reversed Iterator of the given sequence. We can use this reverse iterator to iterate over the contents of the sequence, or we can pass this iterator to list() function, to create a new list of reversed contents of the sequence. Let’s use this reversed() function to get a copy of list with reversed contents,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Get a list with reversed contents
reversed_list = list(reversed(list_of_num))

print(reversed_list)

Output:

[59, 58, 57, 56, 55, 54, 53, 52, 51]

The reversed() function returned a reverse iterator of the given list and then we passed this reverse iterator to the list() function, which iterated over all the elements of the list in reverse order and inserted them to a new list i.e. a list with reversed contents. In the end it returned that reversed list as a copy of the original list.

Get a reversed list using slicing

Python provides a way to slice a list i.e. selecting specific elements from a list based on occurrence pattern and order. Its syntax is,

list[start:stop:step_size]

It selects elements from start to stop -1 by step size.
Facts about Arguments:

  • If start is not provides then it picks elements from 0th index by default
  • If stop is not provides then it picks the elements till the end of list
  • step_size represents the difference between each step i.e. distance between two picked elements. Default value is 1.

We can use this to pick elements from end to start in a list i.e. in reverse order,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Get a reversed list by providing step size as -1
reversed_list = list_of_num[::-1]

print('Reversed list: ')
print(reversed_list)

Output:

Reversed list: 
[59, 58, 57, 56, 55, 54, 53, 52, 51]

It selected elements from end to start of a list in reverse order because step size was -1. The returned reversed list is a copy of the original list.

Get a reversed list using for loop

Create a new empty list. After that, get the size of the original list and then iterate through elements in original list from index position size-1 to 0. While iteration insert them to the new list one by one.

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Create an empty list
reversed_list = []
# loop from 0 to len -1 i.e. size of list
for i in range(len(list_of_num)):
    # Append element at index -i to the new list
    reversed_list.append(list_of_num[-(i+1)])

print('Reversed list: ')
print(reversed_list)

Output:

Reversed list: 
[59, 58, 57, 56, 55, 54, 53, 52, 51]

Our new list contains all the elements from the original list, but in reversed order.

Get a reversed list using list comprehension

Use list comprehension and range() function, iterate over list in reverse order and push elements to a new list.

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Iterate over num 0 to size-1 and select elements from back i.e. -i
reversed_list = [list_of_num[-(i+1)] for i in range(len(list_of_num))]

print(reversed_list)

Output:

[59, 58, 57, 56, 55, 54, 53, 52, 51]

It is more pythonic and one line solution to create a new list with reversed content.

How did it work?

Using the range() function, get a sequence of numbers from 0 to n-1, where n is the size of the list. Then iterate over the sequence of numbers using list comprehension and for each number i in the sequence select element from list at index -(i+1). So, if our list size is 10, then it will select elements in following order,

  • Select element at index -1 i.e. At index 9
  • Select element at index -2 i.e. At index 8
  • Select element at index -3 i.e. At index 7
  • Select element at index -4 i.e. At index 6
  • Select element at index -5 i.e. At index 5
  • Select element at index -6 i.e. At index 4
  • Select element at index -7 i.e. At index 3
  • Select element at index -8 i.e. At index 2
  • Select element at index -9 i.e. At index 1
  • Select element at index -10 i.e. At index 0

So, using list comprehension we iterated over the list in reverse order and created a new list out of these elements.

Reverse the contents of a list in place

Reverse a list in place using reverse() function

Python list class provides a member function reverse(), that reverses the contents of list in place. Here in place means that this function will not create a copy of the existing list, instead it will modify the contents of the list object through which it is called.

Let’s use this to reverse() function to reverse the contents of our list,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Reverse the contents of a list in place
list_of_num.reverse()

print(reversed_list)

Output:

[59, 58, 57, 56, 55, 54, 53, 52, 51]

Reverse a list of lists

Suppose we have a list of list i.e.

# list of lists
list_of_list = [[1 , 2, 3, 4, 5],
                [11, 12, 13, 14, 15],
                [21, 22, 23, 24, 25] ]

Reverse the contents of sub lists / contents of rows in a 2D matrix

List of list is like a 2D matrix, here we will reverse the content of each row in this 2D matrix,

# Use list comprehension to reverse the contents of sub lists
reversed_list = [elem[::-1] for elem in list_of_list]

print('Reversed List of List')
print(reversed_list)

Output:

Reversed List of List
[[5,   4,  3,  2,  1],
 [15, 14, 13, 12, 11],
 [25, 24, 23, 22, 21]]

So, basically we reversed the content of each nested list in the list of lists but the position of nested / sublists remained the same.

Using list comprehension, we iterated over the sub lists of the list and for each sub list we created a new list with reversed contents. All these new lists with reversed contents were added in the new list, to create a list of lists with reversed contents.

Reverse the contents & Order of sub lists

List of list is like a 2D matrix, here we will reverse the content of each row in this 2D matrix and also the reverse the positions of rows in the matrix,

# Use list comprehension to reverse the contents & order of sub lists
reversed_list = [elem[::-1] for elem in list_of_list ][::-1]

print('Reversed List of List')
print(reversed_list)

Output:

[[25, 24, 23, 22, 21],
 [15, 14, 13, 12, 11],
 [5,   4,  3,  2, 1]]

So, basically we reversed the content of each nested list in the list of lists and also reversed their position in the main list.

Using list comprehension, we iterated over the sub lists of the list and for each sub list we created a new list with reversed contents. All these new lists with reversed contents were added in the new list, to create a list of lists with reversed contents. Then we reversed the new main list to reverse the order of sub lists.

Reverse a part or slice of a list in Python

Suppose we have a list of numbers,

# list of numbers
list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

We want to reverse a small portion of the list. Like in the above list we want to reverse the contents from index 2 to 5. result should be like,

[51, 52, 56, 55, 54, 53, 57, 58, 59]

Now to reverse a part of the list, we will slice the list using [] notation to separate out that part. Then we will reverse that separated out part & merge it back. For example, to reverse the contents of from index a to b, use the following expression,

reversed_list= list_of_num[0:a] + list_of_num[b:a-1:-1] + list_of_num[b+1:]

let’s see how to reverse the contents from index 2 to 5 in the list,

# Reverse the part of list i.e. from index 2 to 5
reversed_list= list_of_num[0:2] + list_of_num[5:1:-1] + list_of_num[6:]

print('List with reversed part')
print(reversed_list)

Output:

List with reversed part
[51, 52, 56, 55, 54, 53, 57, 58, 59]

Algorithm to reverse list items in place using for loop

In all the above solutions either we used some built-in functions or some tricks. Suppose instead of using any function, we want to implement our algorithm.

Algorithm which we want to implement is as follows,

  • Iterate over items of the list by index position till size /2 and for each element at index i:
    • swap values at index i with index -(i+1)

Let’s see how to implement this algo,

# list of numbers
list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Iterate over items if list by index position
for i in range(int( len(list_of_num) / 2)):
    # Swap items at index i with -(i+1)
    temp = list_of_num[i]
    list_of_num[i] = list_of_num[-(i+1)]
    list_of_num[-(i + 1)] = temp

print(list_of_num)

Output:

[59, 58, 57, 56, 55, 54, 53, 52, 51]

It reversed the contents of the list.
Now instead of writing 3 lines of code for swapping elements, we can do that in a single line and reverse the contents of list by swapping elements,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Iterate over items if list by index position
for i in range(int( len(list_of_num) / 2)):
    # Swap items at index i with -(i+1)
    list_of_num[i], list_of_num[-(i+1)] = list_of_num[-(i+1)],list_of_num[i]

print(list_of_num)

Output:

[59, 58, 57, 56, 55, 54, 53, 52, 51]

So these were the different ways to reverse the contents of a list or list of lists.

The complete example is as follows,

def main():
    list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

    print('Original List:')
    print(list_of_num)

    print('*** Get a reversed list using reversed() function ***')

    # Get a list with reversed contents
    reversed_list = list(reversed(list_of_num))

    print('Reversed list: ')
    print(reversed_list)

    print('*** Get a reversed list using Slicing ***')

    # Get a reversed list by providing step size as -1
    reversed_list = list_of_num[::-1]

    print('Reversed list: ')
    print(reversed_list)

    print('*** Get a reversed list using for loop ***')
    # Create an empty list
    reversed_list = []
    # loop from 0 to len -1 i.e. size of list
    for i in range(len(list_of_num)):
        # Append element at index -i to the new list
        reversed_list.append(list_of_num[-(i+1)])

    print('Reversed list: ')
    print(reversed_list)

    print('*** Get a reversed list using list comprehension ***')

    # Iterate over num 0 to size-1 and select elements from back i.e. -i
    reversed_list = [list_of_num[-(i+1)] for i in range(len(list_of_num))]
    print(reversed_list)

    print('**** Reverse the contents of a list in place ****')

    # Reverse the contents of a list in place
    list_of_num.reverse()

    print(reversed_list)


    print('*** Reverse a list of lists ***')

    # list of lists
    list_of_list = [[1 , 2, 3, 4, 5],
                    [11, 12, 13, 14, 15],
                    [21, 22, 23, 24, 25] ]

    print('Reverse the contents of sub lists / contents of rows in 2D matrix')

    # Use list comprehension to reverse the contents of sub lists
    reversed_list = [elem[::-1] for elem in list_of_list]

    print('Reversed List of List')
    print(reversed_list)

    print('Reverse the contents of sub lists and their order')

    # Use list comprehension to reverse the contents & order of sub lists
    reversed_list = [elem[::-1] for elem in list_of_list ][::-1]

    print('Reversed List of List')
    print(reversed_list)

    print('**** Reverse a part (slice) of a list in Python ****')

    # list of numbers
    list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

    # Reverse the part of list i.e. from index 2 to 5
    reversed_list= list_of_num[0:2] + list_of_num[5:1:-1] + list_of_num[6:]

    print('List with reversed part')
    print(reversed_list)

    print('**** Algorithm to reverse list items in place using for loop ****')

    print('Method 1:')
    # list of numbers
    list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

    print('Original List:')
    print(list_of_num)

    # Iterate over items if list by index position
    for i in range(int( len(list_of_num) / 2)):
        # Swap items at index i with -(i+1)
        temp = list_of_num[i]
        list_of_num[i] = list_of_num[-(i+1)]
        list_of_num[-(i + 1)] = temp

    print('Updated List:')
    print(list_of_num)

    print('Method 2:')
    list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

    print('Original List:')
    print(list_of_num)

    # Iterate over items if list by index position
    for i in range(int( len(list_of_num) / 2)):
        # Swap items at index i with -(i+1)
        list_of_num[i], list_of_num[-(i+1)] = list_of_num[-(i+1)],list_of_num[i]

    print('Updated List:')
    print(list_of_num)


if __name__ == '__main__':
   main()

Output

Original List:
[51, 52, 53, 54, 55, 56, 57, 58, 59]
*** Get a reversed list using reversed() function ***
Reversed list: 
[59, 58, 57, 56, 55, 54, 53, 52, 51]
*** Get a reversed list using Slicing ***
Reversed list: 
[59, 58, 57, 56, 55, 54, 53, 52, 51]
*** Get a reversed list using for loop ***
Reversed list: 
[59, 58, 57, 56, 55, 54, 53, 52, 51]
*** Get a reversed list using list comprehension ***
[59, 58, 57, 56, 55, 54, 53, 52, 51]
**** Reverse the contents of a list in place ****
[59, 58, 57, 56, 55, 54, 53, 52, 51]
*** Reverse a list of lists ***
Reverse the contents of sub lists / contents of rows in 2D matrix
Reversed List of List
[[5, 4, 3, 2, 1], [15, 14, 13, 12, 11], [25, 24, 23, 22, 21]]
Reverse the contents of sub lists and their order
Reversed List of List
[[25, 24, 23, 22, 21], [15, 14, 13, 12, 11], [5, 4, 3, 2, 1]]
**** Reverse a part (slice) of a list in Python ****
List with reversed part
[51, 52, 56, 55, 54, 53, 57, 58, 59]
**** Algorithm to reverse list items in place using for loop ****
Method 1:
Original List:
[51, 52, 53, 54, 55, 56, 57, 58, 59]
Updated List:
[59, 58, 57, 56, 55, 54, 53, 52, 51]
Method 2:
Original List:
[51, 52, 53, 54, 55, 56, 57, 58, 59]
Updated List:
[59, 58, 57, 56, 55, 54, 53, 52, 51]

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top