Python sorted() Function – Tutorial with Examples

The sorted() function in Python is a built-in function that returns a sorted list of elements from a given iterable. It can sort any iterable object, including lists, tuples, and dictionaries. By default, the sorted() function sorts the elements in ascending order, but it can also sort in descending order by passing the argument reverse=True.

Syntax

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

Parameters

  • iterable : The iterable object to be sorted. This can be a list, tuple, dictionary, or any other iterable object.
  • key : A function that returns a value that will be used for sorting. The elements in the iterable are sorted based on the values returned by the key function.
  • reverse : If set to True, the elements in the iterable will be sorted in descending order. The default value is False.

Return Value

The sorted() function returns a sorted list of elements from the given iterable.

Examples

Example 1: Sorting a List of Numbers

# Sorting a list of numbers
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)

Output

[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

Example 2: Sorting a List of Strings

# Sorting a list of strings
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words)
print(sorted_words)

Output

['apple', 'banana', 'cherry', 'date']

Example 3: Sorting a List of Tuples

# Sorting a list of tuples
students = [('John', 80), ('Jane', 90), ('Jim', 85), ('Jack', 95)]
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
print(sorted_students)

Output

[('Jack', 95), ('Jane', 90), ('Jim', 85), ('John', 80)]

Use Cases

The sorted() function is often used in the following scenarios:

  • Sorting a list or any iterable object in ascending or descending order.
  • Sorting a list of dictionaries or tuples based on specific keys or values.
  • Sorting the elements in a list of custom objects based on a specific attribute or property.
  • Sorting the elements in a list based on multiple criteria.

In conclusion, the sorted() function is a simple and efficient tool for sorting elements in a list or any iterable object in Python. It provides various options to sort elements based on specific criteria, making it a versatile tool for sorting elements in different scenarios.

Leave a Reply

Your email address will not be published. Required fields are marked *