Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Types of Methods to Reverse a List
3.
reverse() Method 
3.1.
Syntax 
3.2.
Example
3.3.
Output
4.
reversed() Method 
4.1.
Syntax
4.2.
Example
4.3.
Output
4.4.
Explanation
4.5.
Get the Returned Object
4.6.
Output
4.7.
Using list() constructor
4.8.
Output
5.
Slicing Method
5.1.
Syntax
5.2.
Example 
5.3.
Output
6.
Frequently asked questions
6.1.
Are lists and strings the same in Python?
6.2.
How can you skip letters in slicing strings?
6.3.
What makes Python so popular?
7.
Conclusion 
Last Updated: Mar 27, 2024
Easy

What is reverse in python?

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

As you know, a list in python is nothing but a standard data type of Python that can store a sequence of values belonging to any kind. In other words, Python lists are containers for storing values of any type. 

For example, the following are some Python lists:

[1, 2, 3]                      # list of integers
['a', 'b', 'c']                # list of characters
['a', 1, 'b', 3.9, 'zero']     # list of mixed value types
['One', 'Two', 'Three']        # list of strings


Here, python list reverse means reversing the elements of the list. 

The most significant aspect of Python Lists is that they are mutable, which means you can alter the elements of a list. Python will not create a new list when you change a list member. This way, we play around with the list. 

Let us understand with the help of an example: 

10 12 56 87 100

 

After Reversing, the list must look like this: 

100 87 56 12 10.

 

How to achieve this is a question. 

This article will discuss multiple ways to reverse a list in python. So, let us get started: 

How to reverse a list in python

Types of Methods to Reverse a List

There are generally three methods by which python list reverse can occur. Below are the following: 

  1. reverse() method 
  2. reversed() method 
  3. Slicing method
     

Let us discuss each method one by one: 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

reverse() Method 

Python List reverse() is a built-in method in the Python programming language that reverses List objects in place, which means it doesn't take up any extra space and only modifies the original list.

Since this function overwrites the original list, it cannot be accessed (it can only be retrieved by reversing the string). This means that if you want the original list, you must apply the reverse()  method again. 

reverse

Syntax 

listName.reverse()

Parameters

No Parameters

Return Value 

No return value, as the original list is modified. 

Example

# create a list of numbers
numbers = ['One', 'Two', 'Three']
# Modifies the original list 
numbers.reverse()
# display the output 
print(numbers)

Output

['Three', 'Two', 'One']

reversed() Method 

The built-in reversed function in Python is used to reverse a sequence, such as a list, string, or tuple, by creating a reverse iterator of the given sequence.
 

Note: reversed() method is similar to the iter() but in reverse order. 

Syntax

reversed(listName)

Parameters

Name of the Sequence such as a list, tuple. 

Return Value 

reverse iterator object

 

Example

# create a list of numbers
numbers = ['One', 'Two', 'Three']
# reverse iterator object
result = reversed(numbers)
print(result)

Output

<list_reverseiterator object at 0x7f90370d3460>

Explanation

The above code has one list of numbers that is passed as a parameter to the reversed() function. reversed() function, as discussed, will return the iterator object that can be iterated through the loops in python. The output indicates the same. 

Let us now try to iterate through the returned object. 

Get the Returned Object

# create a list of numbers
numbers = ['One', 'Two', 'Three']
# reverse iterator object
result = reversed(numbers)
# display the output 
for element in result:
    print(element , end =' ')

Output

Three Two One

 

The issue here is that the elements are printed separately, and what if we want them all in reverse order in the list? We can use the list() constructor over the result of the reversed() function.

Using list() constructor

# create a list of numbers
numbers = ['One', 'Two', 'Three']
# reverse iterator object
print(list(reversed(numbers)))

Output

['Three', 'Two', 'One']

Slicing Method

Python has come up with an interesting feature that is List Slicing.

Syntax

listName[start:stop:step]

Parameters

Description

Start

Start specifies the value from which the user wants to iterate or slice the list.

Stop

The Stop parameter specifies the value until the user wishes to slice or iterate the list. 

Step

The step parameter specifies the value with which the user wishes to skip the elements between the list's start and stop indexes.

 

In python, Lists index their elements in two ways:

forward indexing as 0, 1, 2, 3,… And backward indexing as -1, -2, -3, …

indexing

The image above indicates that the elements of the list can be accessed using two-way indexing, as shown below:

illustrative_diagram

Individual elements of a list are accessed in Python via their indexes. If you pass a negative index while accessing list elements, Python adds the length of the list to the index to get the element's forward index. That is, for a 6-element list L, L[-5] will be computed internally as L[-5+6] = L[1], and so on. This is how backward indexing works in lists.

Henceforth, [ : : -1] If you only pass -1 as a step parameter, the list will be printed in reverse order.

Check out this problem - Reverse Nodes In K Group

Must Read Python List Operations

Let us understand with an example: 

Example 

# create a list of numbers
numbers = ['One', 'Two', 'Three']
print(numbers[::-1])

Output

['Three', 'Two', 'One']

 

Also read reverse a number.

Frequently asked questions

Are lists and strings the same in Python?

No, a string is an ordered sequence of characters, whereas a list is an ordered sequence of object types.

How can you skip letters in slicing strings?

You need to pass the step parameter along with starting index and end index to skip letters in slicing strings.

What makes Python so popular?

Python is one of the most loved user-friendly programming languages available because of its simple syntax and emphasis on natural language.

Conclusion 

To summarise the article, we have thoroughly discussed How to Reverse a List in Python. We discussed three methods: reverse, which modifies the original string, reversed, which returns the reverse iterator of the given sequence, and slice operator in which we used the concept of Forward and Backward Indexing. 

After reading the article, do you feel more excited to read/explore more articles on Python? Don't worry; Coding Ninjas has you covered. 

See Exception & Errors in PythonShort-Circuiting in PythonLambda Function in Python, and File Handling in Python.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Python programming language, Competitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Happy Learning!

Previous article
List Length in Python
Next article
Python List Operations
Live masterclass