Python built-in Method - reversed()
The reversed()
function is a built-in Python method that returns a reverse iterator for a sequence. The sequence can be a list, a tuple, a string, or any other iterable object.
The syntax for the reversed()
function is as follows:
reversed(seq)
seq
: The sequence to be reversed.
Here are some examples of how the reversed()
function can be used:
>>> lst = [1, 2, 3, 4, 5] >>> for i in reversed(lst): ... print(i) ... 5 4 3 2 1
In this example, we use the reversed()
function to get a reverse iterator for the lst
list. We then use a for
loop to iterate over the reversed sequence and print each value.
>>> s = "hello" >>> for c in reversed(s): ... print(c) ... o l l e h
In this example, we use the reversed()
function to get a reverse iterator for the s
string. We then use a for
loop to iterate over the reversed sequence and print each character.
>>> x = (1, 2, 3, 4, 5) >>> y = reversed(x) >>> print(list(y)) [5, 4, 3, 2, 1]
In this example, we use the reversed()
function to get a reverse iterator for the x
tuple. We then use the list()
constructor to convert the reversed iterator to a list and print the result.
The reversed()
function is a simple but useful built-in method in Python that provides a convenient way to iterate over a sequence in reverse order. It is often used in conjunction with for
loops and list comprehensions to perform operations on a sequence in reverse order.