Open In App

Python sorted() Function

Python sorted() function returns a sorted list. It is not only defined for the list and it accepts any iterable (list, tuple, string, etc.).

Example






print(sorted([4, 1, 3, 2]))

Output
[1, 2, 3, 4]

Python sorted() Function Syntax

sorted(iterable, key, reverse)



Parameters:

Return: Returns a list with elements in sorted order.

How to Use sorted() Function in Python?

Using sorted() function is very easy. It is a built in function in Python and can be used with any iterable. Let’s understand it better with a example:

Example:




# creating a list
counting = [4,1,5,2,3]
#print sorted list
print(sorted(counting))

Output
[1, 2, 3, 4, 5]

More Sorted() Function Examples

Lets look at some of the use cases of sorted() function:

1. Sorting a Python list using sorted() function

In this example, we have applied sorted on the Python list.




x = [2, 8, 1, 4, 6, 3, 7]
  
print("Sorted List returned :", sorted(x))
  
print("Reverse sort :", sorted(x, reverse=True))
  
print("\nOriginal list not modified :", x)

Output
Sorted List returned : [1, 2, 3, 4, 6, 7, 8]
Reverse sort : [8, 7, 6, 4, 3, 2, 1]

Original list not modified : [2, 8, 1, 4, 6, 3, 7]

2. Sorting different data types with sorted() function

In this example, we have used sorted() on different datatypes like list, tuple, string, dictionary, set, and frozen set.




# List
x = ['q', 'w', 'r', 'e', 't', 'y']
print(sorted(x))
  
# Tuple
x = ('q', 'w', 'e', 'r', 't', 'y')
print(sorted(x))
  
# String-sorted based on ASCII translations
x = "python"
print(sorted(x))
  
# Dictionary
x = {'q': 1, 'w': 2, 'e': 3, 'r': 4, 't': 5, 'y': 6}
print(sorted(x))
  
# Set
x = {'q', 'w', 'e', 'r', 't', 'y'}
print(sorted(x))
  
# Frozen Set
x = frozenset(('q', 'w', 'e', 'r', 't', 'y'))
print(sorted(x))

Output
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['h', 'n', 'o', 'p', 't', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']

3. Reverse sorting using Python sorted()

Sorting a string in lexicographically reverse order by setting reverse=True in the sorted() function.




# Python3 code to demonstrate
# Reverse Sort a String
# using join() + sorted() + reverse
    
# initializing string 
test_string = "geekforgeeks"
    
# printing original string 
print("The original string : " + str(test_string))
    
# using join() + sorted() + reverse
# Sorting a string 
res = ''.join(sorted(test_string, reverse = True))
        
# print result
print("String after reverse sorting : " + str(res))

Output
The original string : geekforgeeks
String after reverse sorting : srokkggfeeee

4. Python Sorted() with lambda

Using sorted() inside the Python lambda function.




import functools
test_string = "geekforgeeks"
  
print("The original string : " + str(test_string))
# using sorted() + reduce() + lambda
res = functools.reduce(lambda x, y: x + y,
                       sorted(test_string, 
                              reverse=True))
print("String after reverse sorting : " + str(res))

Output
The original string : geekforgeeks
String after reverse sorting : srokkggfeeee

5. Sorted() in Python with len()

In this example, we are sorting the list based on its length. The string of the smallest length should come first.




L = ["cccc", "b", "dd", "aaa"]
print("Normal sort :", sorted(L))
print("Sort with len :", sorted(L, key=len))

Output
Normal sort : ['aaa', 'b', 'cccc', 'dd']
Sort with len : ['b', 'dd', 'aaa', 'cccc']

The key can also take user-defined functions as its value for the basis of sorting.

Example:




# Sort a list of integers based on
# their remainder on dividing from 7
def func(x):
    return x % 7
  
L = [15, 3, 11, 7]
  
print("Normal sort :", sorted(L))
print("Sorted with key:", sorted(L, key=func))

Output
Normal sort : [3, 7, 11, 15]
Sorted with key: [7, 15, 3, 11]

6. Sorting a list in ascending order with sorted()

In my_list, we have a list of integer values. We then use the sorted function to sort the list in ascending order. The sorted function takes the iterable to be sorted as its first argument and returns a new list that contains the sorted elements.

In my_string, we have a string. We then use the sorted function to sort the characters in the string in ascending order. The sorted function treats the string as an iterable of characters and returns a new list that contains the sorted characters.

In my_tuples, we have a list of tuples that contains integers and strings. We have used the sorted function to sort the list based on the second element of each tuple. To achieve this we have passed a lambda function as the key argument to the sorted function.




my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_list = sorted(my_list)
print(sorted_list)  
  
my_string = "hello, world!"
sorted_string = sorted(my_string)
print(sorted_string)  
  
my_tuples = [(1, "one"), (3, "three"), (2, "two"), (4, "four")]
sorted_tuples = sorted(my_tuples, key=lambda x: x[1])
print(sorted_tuples)

Output
[1, 1, 2, 3, 4, 5, 5, 6, 9]
[' ', '!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

7. Sorting a List of Dictionaries by a Specific Key using sorted()

In this example, we are sorting the list of dictionaries with a specific key.




students = [
    {'name': 'John', 'age': 20},
    {'name': 'Alice', 'age': 18},
    {'name': 'Bob', 'age': 22}
]
sorted_students = sorted(students,key=lambda x: x['age'])
print(sorted_students)

Output
[{'name': 'Alice', 'age': 18}, {'name': 'John', 'age': 20}, {'name': 'Bob', 'age': 22}]

8. Sorting a List of Custom Objects

In this example, we are creating a custom class named Person with two instance variables name and age and we are creating three objects of the Person class and inserting objects into lists. We are using the Sorted Function which sorting the Person’s objects.




class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
  
    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"
  
  
people = [
    Person('John', 25),
    Person('Alice', 18),
    Person('Bob', 30)
]
sorted_people = sorted(people, key=lambda x: x.age)
print(sorted_people)

Output
[Person(name='Alice', age=18), Person(name='John', age=25), Person(name='Bob', age=30)]

We have covered the definition, syntax and examples of sorted() function in Python. Hope this has answered your question on ” How to use sorted function in Python?”.

sorted() function should not be confused with sort() list method, as they are different.

Hope this article helped you in understanding sorted() function in Python.


Article Tags :