Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
reverse
communitycreator

How to use reverse() in Python

Sarah Tanveer

The built-in Python reverse() function is used to reverse the order of objects in a list data structure in place.

Syntax

list.reverse()
list1.reverse() will change the order of the objects in the list, as shown in the diagram

Parameters

This function takes no parameters.

Return value

  • This function does not return anything.

  • The list that calls the function is updated in place.

  • If the function is called by an object that is not a list, an Attribute Error is returned.

Code

# creating a list 
listTest1 = [5, 4, 3, 2, 1]   

# printing the list
print("list before reversing: ")
print(listTest1)              

# call reverse on first list
listTest1.reverse()           
print("\nlist after reversing: ")
print(listTest1) # list is updated

# creating another list 
listTest2 = ["one", "two", "three", "four", "five"]

# printing second list
print("\nlist before reversing: ")
print(listTest2)              

# call reverse on second list
listTest2.reverse()           
print("\nlist after reversing: ")
print(listTest2) # list is updated           

# this will throw Attribute Error
notAList = 536

# calling reverse with an onject that is not a list
notAList.reverse()  

reverse() vs. reversed()

The reversed() function takes any sequence as an argument and returns a reversed iterator object. The iterator object accesses the objects of the sequence in reverse order.

On the other hand, reverse() does not take any arguments, nor does it return anything. The changes are made to the original list itself.

RELATED TAGS

python
reverse
communitycreator
RELATED COURSES

View all Courses

Keep Exploring