Difference between sort and sorted functions in Python

Why Sort Lists?

We often need to sort the elements of a list for various reasons like searching for elements, merging elements, optimizing list performance and readability etc. In Python we can use 'sort' and 'sorted' functions to sort a list. While both functions can be used to sort a list there are some differences in the usage of these functions that should be kept in mind before using one over the other.

Sorted

Sorted function (built-in) takes a list as argument (along with other optional arguments) and returns a new list with elements of original list sorted in ascending or descending order.

 

    Output:

To sort the list in descending order, add reverse = True with the list argument. 


    Output:



Sort

Sort function/ method will sort the original list without the need of creating a new list. It is applied on the list object rather than taking the list as an argument.

    Output:


Keep in mind that you should not assign the sort function to a new list as it will not return anything. 

    Output:


Sorting string literals

We can also use sorted function to sort string literals. By default, it sorts capital letters first and then small case letters in alphabetical order. To sort a string without considering capitalization, we can use a keyword argument called casefold.

    Output:
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', 'T', 'a', 'a', 'a', 'b', 'd', 'd', 'd', 'd', 'e', 'e', 'g', 'i', 'i', 'o', 'o', 'o', 'o', 'o', 's', 's', 't', 't', 'u', 'y', 'y']

using casefold:


    Output:

[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'a', 'a', 'a', 'b', 'd', 'd', 'd', 'd', 'e', 'e', 'g', 'i', 'i', 'o', 'o', 'o', 'o', 'o', 's', 's', 'T', 't', 't', 'u', 'y', 'y']

This case-insensitive sorting is particularly useful when you have a list of names, items etc. and you need to sort them alphabetically.


names = ["Jordan", "jane", "Peter", "Ian", "Eric", "ana"]
names.sort()
print("Case sensitive sorting: ", names)
names.sort(key = str.casefold)
print("Case insensitive sorting: ", names)

Output:

Case sensitive sorting:  ['Eric', 'Ian', 'Jordan', 'Peter', 'ana', 'jane']
Case insensitive sorting:  ['ana', 'Eric', 'Ian', 'jane', 'Jordan', 'Peter']

Note: we used sort twice in above code snippet which means first we sorted the original list and then we sorted the case sensitive sorted list from first sort operation. 

     
































Comments

Popular posts from this blog

Modulo Multiplication Patterns using Python