Python sorted() Built in Function
The sorted() function in Python returns a new sorted list from the items in an iterable. The syntax is:
sorted(iterable, key=None, reverse=False)
where iterable is any sequence or collection that supports iteration, key is a function that defines the sorting order and reverse is a boolean value that indicates whether to sort in ascending or descending order. If any of these parameters are omitted, they default to None and False respectively.
Here are some examples of using sorted() with different iterables:
# Create a list of numbers
my_list = [6 ,9 ,3 ,1]
# Use sorted() to get a new sorted list
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1 ,3 ,6 ,9]
# Use sorted() with reverse parameter
sorted_list = sorted(my_list, reverse=True)
print(sorted_list) # Output: [9 ,6 ,3 ,1]
# Create a string
my_string = "Python Programming"
# Use sorted() to get a new sorted list of characters
sorted_string = sorted(my_string)
print(sorted_string) # Output: [' ', 'P', 'P', 'a', 'g', 'g', 'h', 'i', 'm', 'm', 'n', 'n', 'o', 'r', 't', 'y']
# Use sorted() with key parameter
sorted_string = sorted(my_string, key=str.lower)
print(sorted_string) # Output: [' ', 'a', 'g', 'g', 'h', i' ,'m' ,'m' ,'n' ,'n' ,'o' ,'P' ,'p' ,'r' ,'t' ,'y']
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment