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.

Advertisements

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.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

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