Python reversed() Built in Function

The reversed() function is used to return a reversed iterator object of a given sequence object. The syntax of this function is:

reversed(sequence)

The sequence parameter is required and specifies the sequence object (such as list, tuple, string, range) whose reverse order is needed. The reversed() function returns an iterator object that can be used with for loops or converted to a list using list() function.

The reversed() function can be useful for reversing the order of elements in a sequence without modifying the original sequence. It can also be used with sorted() function to sort a sequence in descending order. Here are some examples of using the reversed() function in Python:


To reverse the order of a string and print each character:

s = "Python"
r = reversed(s)
for c in r:
    print(c)
# prints n o h t y P

To reverse the order of a list and create a new list:

l = [1, 2, 3, 4, 5]
r = reversed(l)
new_l = list(r)
print(new_l)
# prints [5, 4, 3, 2, 1]

To sort a list in descending order using reversed() and sorted() functions:

l = [5, 2, 4, 1, 3]
r = reversed(sorted(l))
print(list(r))
# prints [5, 4 ,3 ,2 ,1]

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions