reversed() Function in Python

Python reversed() Function

In Python, the reversed() function is a built-in function that returns a reverse iterator for a given sequence, such as a list, tuple, string, or range. The reverse iterator allows you to iterate through the elements of the sequence in reverse order, starting from the last element and moving towards the first one.

The reversed() function takes a single argument, which should be a sequence, and returns a reverse iterator. The syntax is as follows:

reversed(sequence)

Here's an example of how to use the reversed() function with different types of sequences:

Using reversed() with a list:

my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)  # Output: [5, 4, 3, 2, 1]

Using reversed() with a tuple:

my_tuple = (10, 20, 30, 40, 50)
reversed_tuple = tuple(reversed(my_tuple))
print(reversed_tuple)  # Output: (50, 40, 30, 20, 10)

Using reversed() with a string:

my_string = "Hello"
reversed_string = ''.join(reversed(my_string))
print(reversed_string)  # Output: "olleH"

Using reversed() with a range:

my_range = range(1, 6)
reversed_range = list(reversed(my_range))
print(reversed_range)  # Output: [5, 4, 3, 2, 1]

Keep in mind that the reversed() function does not modify the original sequence; it only provides an iterator to traverse the sequence in reverse order. If you need to create a new reversed sequence (e.g., a reversed list or string), you can use the list() or tuple() function to convert the reverse iterator into the desired data type.