Skip to main content

sorted()

The sorted() function in Python is a built-in function used to sort iterables such as lists, tuples, and strings. It returns a new sorted list without modifying the original one. You can also pass in optional parameters like reverse=True to get the list sorted in descending order.

Parameter Values

Parameter Description
iterable

A sequence (e.g., list, tuple) or collection (e.g., dictionary, set) which is to be sorted.

key

A function that serves as the key for the sort comparison. Elements will be sorted based on the value returned by this function.

reverse

A boolean value. If set to True, the iterable will be sorted in reverse order.

return

A new list containing all items from the iterable in ascending order by default, or in descending order if reverse=True.

Return Values

The sorted() function returns a new sorted list from the items of any iterable.

How to Use sorted() in Python

Example 1:

The sorted() function returns a sorted list of the specified iterable object.

fruits = ['apple', 'banana', 'cherry']
sorted_fruits = sorted(fruits)
print(sorted_fruits)
Example 2:

The sorted() function can be used with custom sorting logic by providing a key function.

numbers = [5, 1, 3, 2, 4]
sorted_numbers = sorted(numbers, key=lambda x: x % 3)
print(sorted_numbers)
Example 3:

The sorted() function can be used to sort dictionaries by their keys or values.

stocks = {'GOOGL': 1500, 'AAPL': 2000, 'AMZN': 1800}
sorted_stocks_by_value = sorted(stocks.items(), key=lambda x: x[1])
print(sorted_stocks_by_value)