How to Use sorted() and sort() in Python

Posted in /   /  

How to Use sorted() and sort() in Python
vinaykhatri

Vinay Khatri
Last updated on March 28, 2024

    There are many sorting algorithms in Computer Science, and as a Programmer and coder, you will have to sort the data or items at some point. Many problem algorithms include data sorting, and in Python, you do not have to write a sorting algorithm from scratch; instead, you can either use the python sorted() function or list sort() method.

    In this Python tutorial article, we will learn how to sort data present in different Python data structures. Here we will cover the two commonly used Python methods sorted() and sort(), and by the end of this tutorial will have a complete idea about:

    • How to sort a basic Python data structure.
    • What is the difference between sorted() and .sort()
    • How to customize the sort order and sort data in ascending and descending order.

    Prerequisites for this tutorial

    Sort or Order values using Python sorted() Function.

    The Python sorted() method can accept an iterable object such as string, list, set, tuple, list, and dictionary, and return a list of ordered values in ascending order.

    Sorting Numbers using sorted() method

    We can sort a list of numbers using the sorted() method. In the example below, we have created a list numbers and passed that list as a parameter to the Python sorted() method.

    Example

    >>> numbers = [3,2,5,7,10,11,5]
    >>> sorted(numbers)
    [2, 3, 5, 5, 7, 10, 11]
    
    >>> numbers
    [3, 2, 5, 7, 10, 11, 5]

    Behind the code

    From the above example, we learned four things about sorted() method.

    • That it is a Python in-built method.
    • It needs an iterable object as a parameter.
    • It sorts the elements of the iterable object in ascending order and returns a copy of the sorted list.
    • The original iterable does not get affected.

    Sort a String using the sorted() method

    A string is also iterable and using the sorted() method, we can sort string letters based on their ASCII values.

    Example

    >>> string_numbers = '34782'
    >>> sorted(string_numbers)
    ['2', '3', '4', '7', '8']
    
    >>> string = "hello world"
    >>> sorted(string)
    [' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
    
    >>> string2 ="Hello World"
    >>> sorted(string2)
    [' ', 'H', 'W', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r']

    Behind the code

    From the above example, you can see that the sorted() method split the string into individual letters and then sort it according to their ASCII values. If you want to sort the string value based on the words, not letters, then you can use the .split() method to create a list of strings words.

    Example

    >>> string = "hello world it's techgeekbuzz"
    >>> sorted(string.split())
    ['hello', "it's", 'techgeekbuzz', 'world']

    Python sorted() method Limitations.

    There are two significant limitations in sorted() method, and you must be aware of these two limitations before applying sorted() method on your data structure.

    Sorted() method cannot compare different data types.

    The sorted() method throws TypeError if the iterable object contains different data types elements.

    Example

    >>> diff_type = [1, '2', '3', 4, None]
    >>> sorted(diff_type)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: '<' not supported between instances of 'str' and 'int'

    String Sorting Case dependency

    If you apply the sorted() method on the string, the sorted() method uses the individual character's ASCII value to compare and then sort the character. The ASCII value of A-Z range from 65 to 90, and a-z range from 97 to 122.

    Example

    >>> string = ['a', 'A', 'B', 'b', 'z', 'Z']
    >>> sorted(string)
    
    ['A', 'B', 'Z', 'a', 'b', 'z']

    Sort the values in Reverse order using sorted() method

    By default the sorted() method sort the data structure values in ascending order, but this behavior of the method can be changed by specifying the reverse parameter. reverse is the optional parameter of the sorted() method, and by specifying it to True, the sorted()  method sort the data structure value in reverse or descending order.

    Example

    >>> numbers = [2,4,1,5,19,11,20]
    >>> sorted(numbers, reverse = True)
    
    [20, 19, 11, 5, 4, 2, 1]
    >>> string = "Hello World"
    >>> sorted(string, reverse=True)
    ['r', 'o', 'o', 'l', 'l', 'l', 'e', 'd', 'W', 'H', ' ']

    Sorted() Method key Parameter

    key is another optional parameter of the sorted() method. This parameter can accept a function and sort the data structure value based on that function. The key is the most powerful parameter of the sorted() method it can change the complete behavior of the method, so be careful when you pass the key parameter.

    Example

    Let’s sort a list of string based on the length of individual string length.

    >>> str_list = ["hello", "world", "it's",'techgeekbuzz']
    >>> sorted(str_list, key= len)
    
    ["it's", 'hello', 'world', 'techgeekbuzz']

    Sort elements using sort() method

    The sort() method is similar to the sorted() method, but it is a list method(). Which means it can be only used to sort the elements present in a list data structure. Unlike sorted() method it cannot be used for all the Python iterable objects.

    Syntax

    list.sort()
    
    

    Example

    >>> my_list = [3,4,2,6,9]
    >>> my_list.sort()
    >>> my_list
    [2, 3, 4, 6, 9]

    Four major points about list sort() method

    • Sort() method can only be applied on list objects.
    • It does not return a value, which means It return None.
    • It works on the actual list object and make changes on the actual list.
    • If the list contain different data type element then the sort() method throw a Type Error.

    List sort() method with reverse and key parameters

    Like sorted() method the list .sort() method also accepts two optional parameters reverse and key. If the reverse parameter is True then the sort() method sort the list in reverse order. The key parameter sets the base reference on what basis the comparison should take place.

    Example

    Let’s sort list of string in reverse order based on the length of every element.

    >>> str_list = ['aaa', 'bbbb', 'cccc', 'dd', 'eeeee', 'f', 'gggggg']
    >>> str_list.sort(reverse= True, key=len)
    >>> str_list
    ['gggggg', 'eeeee', 'bbbb', 'cccc', 'aaa', 'dd', 'f']

    Behind the code

    By mentioning the key=len , we specify that sort the str_list elements based on the length of every element. And by specifying the reverse =Ture the sort() method sort the list in descending order.

    What is the difference between the sorted() and sort() method?

    sorted() sort()
    sorted() is a built-in Python method, which can sort any type of iterable object, such as List, Set, Dictionary, string and tuple. sort() is a List method that can only sort Python list data structure elements.
    sorted() return a list of sorted values sort() return None value
    sorted() method does not change the actual data structure element. sort() method arrange the list elements in sorted order.
    sorted() method cannot sort different data type values. sort() method also cannot sort different data type values.
    Example
    >>> my_set = {2,1,3,6,18,9,25}
    >>> sorted_set = sorted(my_set)
    >>> print(sorted_set)
    [1, 2, 3, 6, 9, 18, 25]
    >>> my_list = [2,1,3,6,18,9,25]
    >>> sorted_list = my_list.sort()
    >>> print(sorted_list)
    None
    >>> print(my_list)
    [1, 2, 3, 6, 9, 18, 25]

    Conclusion

    Both sort() and sorted() methods can be used to sort the elements of a list. But sort() method is limited to Python list however sorted() method can sort other data structures too. Generally, in Python programming, we use the sorted() method to sort the elements of a data structure, however, sort() method come useful when you want to make changes on the actual list. By default, both the methods sort the data in ascending order, by specifying the reverse parameter to True, we can sort the data in descending order. Both methods also accept a key parameter, which accepts a function and decides the base reference for the value comparison.

    People are also reading:

    Leave a Comment on this Post

    0 Comments