Python reverse() and reversed() with Examples


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

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

Python lists has a built-in reverse() method that can be used to reverse the elements of a given list. There is also a built-in function called reversed() in Python. Unlike reverse(), reversed() function takes a sequences and returns a reverse iterator.

Python List reverse() Method

List reverse() Method Syntax

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

list.reverse()

Python reverse() Examples

Example 1: Reverse a List of Strings

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

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

Result:

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

Example 2: Reverse a List of Numbers

The following illustrate an example of reversing a list of numbers:

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

Result:

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

Python reversed() Function

Python reversed() Syntax

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

reversed(sequence)

Python reversed() Parameter

  • sequence: Required. Any iterable object. Can be a list, tuple, set, dictionary ...

Python revered() Examples

Example 1: Reverse a List of String

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

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

Result:

Yahoo
Twitter
Facebook
Apple
Oracle
Microsoft

Example 2: Reverse a Tuple of Strings

The following example illustrates how to reverse a tuple of strings, and create a list of strings from the reverse iterator using the list constructor:

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

Result:

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

Example 3: 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"])

Result:

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

In this tutorial, we've learned how to use the list revere() method and reversed() function in Python.

Leave a Reply

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