# When and Why to Use Sorted() Function

The sorted() function is a built-in function in Python that can be used to sort any iterable object. It’s widely used for sorting list of strings, numbers etc., both in ascending and descending order. …

Updated November 24, 2023

The sorted() function is a built-in function in Python that can be used to sort any iterable object. It’s widely used for sorting list of strings, numbers etc., both in ascending and descending order.

Below are few examples:

``````# Sorting Lists
numbers = [213, 45, 678]
sorted_numbers = sorted(numbers) # Sorting numbers in ascending order
print(sorted_numbers) #[45, 213, 678]

names = ['John', 'Alice', 'Bob']
sorted_names = sorted(names) # Sorting names in alphabetical order
print(sorted_names) #['Alice', 'Bob', 'John']
``````

The above examples sort lists of numbers and strings. You can also pass a key argument to the sorted function which specifies how the elements should be compared. For example, if you want to sort the names list in descending order, you could use:

``````sorted_names = sorted(names, reverse=True)  # Sorting names in descending order
print(sorted_names)  #['John', 'Bob', 'Alice']
``````

The sorted() function returns a new list of elements from the original iterable object but does not modify the original list.

To sort a list alphabetically you can use:

``````unordered_list = ['Apple', 'Cherry', 'Banana', 'Mango']
sorted_list = sorted(unordered_list)
print(sorted_list)  # ['Apple', 'Banana', 'Cherry', 'Mango']
``````

This will sort the list alphabetically in ascending order. If you want to sort it descendingly, use reverse=True as:

``````unordered_list = ['Apple', 'Cherry', 'Banana', 'Mango']
sorted_list = sorted(unordered_list, reverse=True)  # Sorting list in descending order
print(sorted_list)  #['Mango', 'Banana', 'Cherry', 'Apple']
``````

This is useful when you need to keep the original list unchanged and a new sorted list for further use.