Python sorted() function
Python sorted() function
The sorted() function returns a sorted list of the specified iterable object.
Syntax
sorted(iterable, *, key=None, reverse=False)
Parameter
iterable: It is a required parameter that represents the sequence to sort, list, dictionary, tuple etc.
key: It is an optional parameter that signifies a Function to execute to decide the order.
reverse: It represents a Boolean parameter where the ‘False’ will sort in the ascending order, whereas the ‘True’ will sort in the descending order.
Return
This function returns a new sorted list from the items in iterable.
Example 1
# Python Program explaining
# the sorted() function
#passing the string values
str_bal = ("u", "b", "a", "s", "f", "m", "h", "e")
print("Initial string value:",str_bal)
#sorting the string values
sorted_str = sorted(str_bal)
# priting the sorted string
print("Sorted String: ",sorted_str)
Output
Initial string value: ('u', 'b', 'a', 's', 'f', 'm', 'h', 'e')
Sorted String: ['a', 'b', 'e', 'f', 'h', 'm', 's', 'u']
Example 2
# Python Program explaining
# the sorted() function
#passing the integer values
int_val = (78,12,45,87,12,34)
print("Initial integer value:",int_val)
#sorting the integer values
sorted_str = sorted(int_val)
# priting the sorted integer values
print("Sorted integer: ",sorted_str)
Output
Initial integer value: (78, 12, 45, 87, 12, 34) Sorted integer: [12, 12, 34, 45, 78, 87]
Example 3
# Python Program explaining
# the sorted() function
#passing the values
val = ("Hello","Apple")
print("Initial value:",val)
#sorting the values
sorted_str = sorted(val)
# priting the sorted values
print("Sorted value: ",sorted_str)
Output
Initial value: ('Hello', 'Apple')
Sorted value: ['Apple', 'Hello']
