In Python, the reversed() function is a built-in function that returns a reverse iterator. The reversed() function can be called on any iterable in Python, and the output of the function is an iterator that iterates over the elements of the iterable in reverse order. This can be useful when you need to iterate over an iterable in reverse order, without modifying the original iterable.
The basic syntax for the reversed() function is as follows:
|
reversed(iterable)
|
where iterable is the iterable for which you want to generate a reverse iterator.
Here are some examples of using the reversed() function:
Example 1: Reversing a list
|
x = [1, 2, 3, 4, 5]
for i in reversed(x):
print(i)
|
Output:
In this example, the reversed() function is called on a list of integers [1, 2, 3, 4, 5]. The for loop iterates over the elements of the list in reverse order using the reversed() function, and prints each element to the console.
Example 2: Reversing a string
|
x = "Hello, world!"
for i in reversed(x):
print(i, end="")
|
Output:
!dlrow ,olleH
In this example, the reversed() function is called on a string "Hello, world!". The for loop iterates over the characters of the string in reverse order using the reversed() function, and prints each character to the console. The end="" argument to the print() function is used to prevent the default behavior of printing a newline after each character.
Example 3: Reversing a tuple
|
x = (1, 2, 3, 4, 5)
for i in reversed(x):
print(i)
|
Output:
5
In this example, the reversed() function is called on a tuple of integers (1, 2, 3, 4, 5). The for loop iterates over the elements of the tuple in reverse order using the reversed() function, and prints each element to the console.
Example 4: Reversing a custom object
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
people = [Person("John", 42), Person("Jane", 35), Person("Bob", 27)]
for person in reversed(people):
print(person)
|
Output:
Person(name=Bob, age=27)
In this example, the reversed() function is called on a list of Person objects. The for loop iterates over the elements of the list in reverse order using the reversed() function, and prints each Person object to the console. The __repr__() method is defined in the Person class to generate a string representation of the object.
In conclusion, the reversed() function is a useful tool in Python for iterating over an iterable in reverse order, without modifying the original iterable. The reversed() function can be called on any iterable in Python, and the output of the function