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., |
key | A |
reverse | A |
return | A new |
Return Values
The sorted()
function returns a new sorted list from the items of any iterable.
How to Use sorted()
in Python
The sorted()
function returns a sorted list of the specified iterable object.
fruits = ['apple', 'banana', 'cherry']
sorted_fruits = sorted(fruits)
print(sorted_fruits)
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)
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)