How to reverse a List in Python?

In this article, we will discuss different ways to reverse a List in python.

Table Of Contents

Reverse a List using revesed() function

Python provides a function reversed(). It accepts a sequence as an argument and returns a reverse iterator over the values of the given sequence. We can pass our given list as an argument to the reversed() function, and read elements from list in reverse order using the reverse iterator. The reversed() function does not modify the given list, so we can store the elements returned by reversed iterator to a list. This new list will have the elements in reverse order. For example,

listOfNumbers = [11, 12, 13, 14, 16, 17]

# Reverse the list
listOfNumbers = list(reversed(listOfNumbers))

print(listOfNumbers)

Ouput:

[17, 16, 14, 13, 12, 11]

We reversed the contents of a list.

Reverse a List using Slicing

We can slice a list by providing the start and end index positions, along with the step size. For example,

listOfNumbers[start : end: 2]

It will select every 2nd element from start to end-1 index positions from the list and in left to right direction. If start and end are not provided, then by default it will start from 0 and end will be the last index position of list. So to reverse a list, select all elements from list but with step size -1. It will select elements from end to start i.e. in reverse direction. Then assign them back to the list. It will give an effect that we have reversed the list. For example,

listOfNumbers = [11, 12, 13, 14, 16, 17]

# Reverse the list
listOfNumbers = listOfNumbers[ : : -1]

print(listOfNumbers)

Ouput:

[17, 16, 14, 13, 12, 11]

We reversed the contents of a list.

Summary

We learned how to reverse the contents of a List in Python.

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