Sorted Reverse In Python

Python provides the sorted() function in order to build a new list from provided iterable. We can sort provided iterable in reverse too. The iterable can be a list, string, tuple, or dictionary. In this tutorial we examine different examples of the reverse sort for the string, list, tuple, dictionary event nested list.

sorted() Syntax

The sorted() function has the following syntax.

sorted(ITERABLE,KEY,REVERSE)
  • ITERABLE is a list, string, dictionary, or tuple which will be sorted.
  • KEY is an optional parameter and is used to specify the sorting key for nested tables.
  • REVERSE is a boolean and optional parameter that is used to sort in reverse order.

Reverse Sorted List

The reverse parameter is set to True in order to sort provided list, string, or tuple. The string, list, or tuple is provided as iterable to the sorted() function. The reverse sorted list is returned like below.

names = ["ismail","ahmet","ali","elif"]

reverse_names=sorted(names,reverse=True)

print(reverse_names)
['ismail', 'elif', 'ali', 'ahmet']

Reverse Sorted String

A string is a list of characters that is also iterable. We can reverse sort a string where every character is sorted as reverse and returned as a list.

reverse_name=sorted("ismail",reverse=True)

print(reverse_name)
['s', 'm', 'l', 'i', 'i', 'a']

Reverse Sorted Specific Value In Nested List

Sometimes iterables like lists or tuples may contain items that consist of multiple values. In these cases, we can specify a specific key in order to sort each item. The key parameter of the sorted() function is used to specify the sort key. The best way is to create a function that returns the sort key. In the following example, we use age as the key to creating the take_age() function.

def take_age(person):
   return person[1]

persons=[("ismail",38),("ali",9),("elif",12),("mehmet",28)]

reverse_sorted = sorted(persons,key=take_age)

print(reverse_sorted)
[('ali', 9), ('elif', 12), ('mehmet', 28), ('ismail', 38)]

Leave a Comment