Python reverse() and reversed() with Examples


How to Use reverse() and reversed() in Python

In this tutorial, you'll learn how to use the reverse() list method and reversed() function in Python.

Python lists have a built-in method called reverse(). You can use it to reverse the elements of the list in place.

There is also a built-in function called reversed() in Python. Unlike reverse(), the reversed() function takes a sequence and returns a reverse iterator.

Python reverse() List Method

Python reverse() Syntax

The syntax of the reverse() list method is as follows:

list.reverse()

Python reverse() Examples

Reverse a List of Strings

The following code illustrates an example of reversing a list of strings:

companies = ["Microsoft", "Oracle", "Apple", "Facebook", "Twitter", "Yahoo"]
companies.reverse()
print (companies)

Output:

['Yahoo', 'Twitter', 'Facebook', 'Apple', 'Oracle', 'Microsoft']

Reverse a List of Numbers

The following code illustrates an example of reversing a list of numbers:

numbers = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
numbers.reverse()
print (numbers)

Output:

[1000, 900, 800, 700, 600, 500, 400, 300, 200, 100]

Python reversed() Function

Python reversed() Function Syntax

The syntax of the Python reversed() function is as follows:

reversed(sequence)

Python reversed() Parameter

  • sequence: Required, and can be any iterable object, a list, tuple, set, or dictionary

Python revered() Function Examples

Reverse a List

The following code illustrates an example of how to reverse a list and loop over the returned reverse iterator:

companies = ["Microsoft", "Oracle", "Apple", "Facebook", "Twitter", "Yahoo"]
companies = reversed(companies)
for company in companies:
print (company)

Output:

Yahoo
Twitter
Facebook
Apple
Oracle
Microsoft

Reverse a Tuple

The following code reverses the elements of the tuple and uses the list constructor to create a list of strings from the reverse iterator:

fruits_tuple = ("Apple", "Melon", "Orange", "Watermelon", "Grapefruit", "Mango", "Kiwi")
fruits_list = list(reversed(fruits_tuple))
print (fruits_list)

Output:

['Kiwi', 'Mango', 'Grapefruit', 'Watermelon', 'Orange', 'Melon', 'Apple']

Reverse a List of Dictionaries

The following code reverses a list of dictionaries:

students = [
{"ID": "2001", "Name": "James"},
{"ID": "2002", "Name": "Roland"},
{"ID": "2003", "Name": "John"},
{"ID": "2004", "Name": "Josh"},

]
iterator = reversed(students)
for i in iterator:
print ("ID:", i["ID"], " | " , "Name:", i["Name"])

Output:

ID: 2004 | Name: Josh
ID: 2003 | Name: John
ID: 2002 | Name: Roland
ID: 2001 | Name: James

In this tutorial, you learned the reverse() list method and reversed()function in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *