Python sorted() function

The sorted() function is used to sort the elements of an iterable (such as a list, tuple, or string). The sorted items are returned in a new list, leaving the original iterable unchanged.

Syntax:

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

Parameters:

  • iterable (required): The iterable (list, tuple, or string) you want to sort.
  • key (Optional): A function that serves as a key for the sort comparison. The value this function returns for each element is used for the sorting process.
  • reverse (optional): A boolean value. If set to True, the list elements are sorted in descending order. The default is False.

Return value:

It returns a new list that contains the sorted elements from the provided iterable, even if the input iterable is of a different type (such as a tuple or a string).

Note: There is a sort() method in Python that sorts a list in place modifying the original list. It is faster than the sorted() function for sorting large lists, as it avoids the memory overhead of creating a new list. You can learn more about the sort() method here.

Example: Sorting a list of numbers

my_list = [10, 5, 30, 20]

sorted_list = sorted(my_list)

print(sorted_list)
# Output: [5, 10, 20, 30]

Example: Sorting a tuple of letters

my_tuple = ('c', 'a', 'r')

sorted_tuple = sorted(my_tuple)

print(sorted_tuple)
# Output: ['a', 'c', 'r']

Sorting in descending order

You can sort an iterable (such as a list, tuple, or string) in descending order by setting the reverse parameter of the sorted() function to True.

Here is an example:

my_list = [10, 5, 30, 20]

sorted_list = sorted(my_list, reverse=True)

print(sorted_list)
# Output: [30, 20, 10, 5]

Custom key sorting

You can perform a custom sorting based on keys by using the key parameter of the sorted() function. The key parameter takes a function that generates a sorting key for each element in the iterable. The sorting is then performed based on the keys returned by this function.

Here’s an example that sorts a list of strings based on their length:

my_list = ["python", "is", "awesome"]

sorted_list = sorted(my_list, key=len)

print(sorted_list)
# Output: ['is', 'python', 'awesome']

In this example, the key parameter is used to provide a function (len) that returns the length of each element, instructing the sorted() function to order the list based on the string lengths instead of the default alphabetical order.

You can also create a custom function that implements your desired sorting logic, and pass this function as the key argument to the sorted() function.

Here’s an example that sorts a list of dictionaries based on age key:

people = [
    {"name": "Alice", "age": 50},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 20},
    {"name": "David", "age": 40}
]

def get_age(person):
    return person['age']

# Sorting the list of dictionaries based on the 'age' key
sorted_people = sorted(people, key=get_age)

print(sorted_people)

Output:

[{'name': 'Charlie', 'age': 20}, {'name': 'Bob', 'age': 30}, {'name': 'David', 'age': 40}, {'name': 'Alice', 'age': 50}]