Python sorted reverse Parameters | Example code

The sorted() function sorts the list of elements in a specific orderr and returns it as a list. Using sorted function with reverse Parameters you can reverse the list.

sorted(iterable, key=None, reverse=False)

Defaults sorted reverse set to False (if not provided)

Python sorted reverse Example

Simple example code. You can sort the string, list, and tuple in reverse order. The sorted() function accepts a reverse parameter as an optional argument.

# set
py_set = {'a', 'c', 'b', 'd', 'e'}
print(sorted(py_set, reverse=True))

# dictionary
py_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
print(sorted(py_dict, reverse=True))

# frozen set
frozen_set = frozenset(('A', 'C', 'E', 'D', 'B'))
print(sorted(frozen_set, reverse=True))

Output:

Python sorted reverse

Do comment if you have any doubts and suggestions on this Python sorted() function topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.