Python Built-in Function sorted:

The sorted() is an inbuilt function in Python used to sort the items in the given iterable. However, irrespective of the iterable type, this function returns the results as a list.

Signature

The signature for the sorted() function is as shown below. Here, l is a list returned by this function.

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

Parameters and return type

  • This method takes one or more iterable as a parameter. Thereafter, it also takes two optional parameters key and reverse. Key is a function that would serve as a key or a basis of sort comparison. Reverse specifies the order in which sorting happens. The default value of reverse is False.
  • However, it returns a sorted list of elements.

Python Built-in Function sorted Examples:

Example 1: For example, let us initialize a list and a tuple object with some numbers. Thereafter, we will use the sorted function to sort the elements. As a result, this function returns sorted elements but in a list.

#Initializing
l = [159, 254, 11, 8, 4559, 32]
t=(22,4,331,55)
#Using sorted and printing
print("Sorted list - ",sorted(l))
print("Sorted tuple - ",sorted(t))

Output

Sorted list -  [8, 11, 32, 159, 254, 4559]
Sorted tuple -  [4, 22, 55, 331]

Example 2: We will take a set and a tuple and sort them in descending order. We have to provide the reverse parameter with the value true to accomplish this.

#Initializing
s = {159, 254, 11, 8, 4559, 32}
t=(22,4,331,55)
#Using sorted and printing
print("Sorted set - ",sorted(s,reverse=True))
print("Sorted tuple - ",sorted(t,reverse=True))

Output

Sorted set -  [4559, 254, 159, 32, 11, 8]
Sorted tuple -  [331, 55, 22, 4]

Example 3: In this case, We will take a set containing string and use the string’s length as a parameter to sort the key. So, we have to specify the key parameter.

#Initializing
city={"chennai", "delhi","mumbai", "hyderabad"}
#Using sorted and printing
print(sorted(city,key=len))

Output

['delhi', 'mumbai', 'chennai', 'hyderabad']

Conclusion

The sorted() function returns the list with sorted elements from the iterable depending on the parameters.

References

Happy Learning 🙂