Reversed() Function in Python
In Python, the reversed
function reverses the order of elements in an iterable object.
reversed(x)
Here, the argument x
can be any iterable object (list, tuple, string, etc.).
This function traverses and reads the iterable object in reverse order, from the last to the first element.
Note: The reversed
function does not sort in descending order; it simply reads the elements starting from the last one. To sort an iterable object in descending order, you first need to sort it in ascending order using the sorted() function and then reverse it with reversed(sorted(x)).
A Practical Example
Let's open the Python interpreter and define a string.
string = "1234"
Next, we'll use the reversed
function to traverse the string in reverse.
for i in reversed(string):
print(i)
The script produces the following output:
4
3
2
1
The function processes the elements in reverse order.
How to Sort in Descending Order
To sort any iterable object in descending order, you first need to sort the object.
reversed(sorted(x))
Where the argument x
can be a string, a tuple, or a list.
A Practical Example
For example, if the string is:
string = "2143"
The reversed
function would return the reversed string "3412".
To sort it in descending order, use the combined reversed(sorted())
function.
for i in reversed(sorted(string)):
print(i)
How does it work?
The sorted
function arranges the elements in ascending order ("1234"), while the reversed
function reverses the order ("4321").
The final output is:
4
3
2
1
This way, the elements of the object are sorted in descending order.
And so on.