AppDividend
Latest Code Tutorials

Python List Reverse Example | reverse() Method Tutorial

0 17

Get real time updates directly on you device, subscribe now.

Python List Reverse Example | reverse() Tutorial is today’s topic. The list reverse() method reverses the sorting order of the items. It takes no parameters. The reverse() function doesn’t return any value. It only reverses the elements and updates the list. The method reverse() reverses objects of the list in place.

Python List Reverse Example

The syntax of Python list reverse() method is following.

list.reverse()

The simple example is the following.

# app.py

GoT = ['Jon', 'Tyrion', 'Daenerys']
GoT.reverse()
print (GoT)

See the output.

Python List Reverse Example | reverse() Tutorial

One thing here to remember that it does not do any ascending or descending order in the list. It just simply reverse the list regardless whether the input string is already ordered or not.

List sort() and reverse() combined example

Let’s take a scenario, where first we are sorting the list based on the criteria of length of string item and then reverse that order in the list.

# app.py

def criteria(item):
    return len(item)
GoT2 = ['Jon', 'Tyrion', 'Daenerys']
GoT2.sort(reverse=True, key=criteria)
print (GoT2)
GoT2.reverse()
print (GoT2)

So, in the above example, we are descending the list based on the length of the string item and then reverse that item in the list. So the output is the following.

List sort() and reverse() combined example

If you want to learn how to sort the list then check out my list sort() method article.

Accessing Individual Elements in Reversed Order

Let us access all the item in reverse order.

# app.py

GoT1 = ['Jon', 'Tyrion', 'Daenerys']
GoT1.reverse()
for item in GoT1:
    print (item)

First, we are reverse the order of the list and then print item one by one.

Python list reverse() Tutorial

Finally, Python List Reverse Example | reverse() Tutorial is over.

Leave A Reply

Your email address will not be published.

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