Sorting Lists in Python

Python lists are one of the most powerful and useful data structures. We can use lists to store data sequentially as we do with arrays in javascript or vectors in C++. In this tutorial, we will learn how to sort a list in python. We will use the sort() method of the python list and the python’s built-in sorted() function to sort the list and see some hands-on examples on customizing the sorting as our requirements.

To follow this tutorial, we need to have python installed in our system. If you don’t have python installed, then you can refer to our tutorial on installing python in Linux.

The sort() method

The sort method modifies the original list and writes the new sorted list into the same list without creating an additional memory location, i.e.; it performs mutation. This means that the original list will be destroyed. So we can use this method only to permanently modify the list and don’t need the original version of the list.

By default, the sort() method sorts a list in ascending order, but we can use the sort() method to sort a list in ascending and descending order.

Syntax:

The syntax of the sort() method is shown below.

python_list.sort(key = <function>, reverse = <True/False>)

Parameters:

The sort() method of lists accepts two optional parameters. Both the arguments are keyword-only arguments, which means that we must provide the name of the argument with the value. If we directly pass the argument values, then it will throw an error that it does not accept positional arguments. The two parameters accepted by the sort() method are:

  • Key – The key parameter takes a function name as the argument, and the function is used to decide how to sort the list. It will use its default way while passing the value None. The function must accept one argument and return some operation that is used for ordering. For example, while sorting a list containing strings the default way is alphabetical sorting, but we can also sort the strings by the length of strings using the key parameter. To achieve this, provide a function name that accepts a string argument, and it returns its length. While using the function name in the key parameter, keep in mind that giving the name of the function without parenthesis is not a function call.
  • Reverse – The reverse parameter is used to check whether to reverse the sorting method or not. It takes boolean values of True or False as an argument. If we provide False, then the list will be sorted in the ascending order, while if we provide True, then the list will be sorted in the descending order. The default value of the reverse parameter is False, which means that if we do not pass any argument to the sort() method, then the list will be sorted in ascending order.

Returns:

The sort() method does not return any value. It only performs the sorting operation in the list and modifies the original list.

Examples:

The below example code show a simple illustration of using the sort() method with the default parameters.

# creating a list containing only strings 
list_1 = ["This", "is", "the", "first", "list", "containing", "only", "strings"]
# creating a list containing only numbers
list_2 = [100, 20, 39, 774]
# sorting the lists using default parameter of sort function
list_1.sort()
list_2.sort()
# displaying the two lists
print(list_1)
print(list_2)

In the above example, we have created two lists list_1 and list_2. The list_1 contains only string elements while the list_2 contains only numbers, then we use the sort() method of the lists to sort them. On running the code, we will get the output as shown in the below image.

sorting a list in default order using sort() method
sorting a list in default order using sort() method

In the above output, we can see that the first list list_1 has been sorted in ascending and alphabetical order, which is the string’s default sorting method. Since Python is a case sensitive language, the uppercase, and lowercase are treated separately, so the string “This” with capital T has been in the first position of the list following the lowercase string. The second list, list_2, which contains only numbers, has also been sorted in ascending order, the default sorting order.

In the above example, we sort the list in ascending order, but we can also sort a list in descending order. The following example shows a practical illustration.

# creating a list containing only strings 
list_1 = ["This", "is", "the", "first", "list", "containing", "only", "strings"]
# creating a list containing only numbers
list_2 = [100, 20, 39, 774]
# sorting the lists in descending order
list_1.sort(reverse=True)
list_2.sort(reverse=True)
# displaying the two lists
print(list_1)
print(list_2)

In the above code, we have provided the parameter reverse=True to the sort() method, which means that the list will be sorted in the reverse of the default order, i.e., descending order.

Output:

sorting a list in descending order using the sort() method
sorting a list in descending order using the sort() method

We have sorted lists without any customization. To customize how the list is going to be sorted, for example, let us see the case of sorting a list containing only elements of the string data types. The default way of sorting such lists is alphabetical and in ascending order but assume that for some purpose. We want to sort the list by comparing the length of the strings instead of alphabetically. In such cases, we have to use the key parameter of the sort() method. The key parameter accepts a function name as an argument, and that function is used to customize the sorting method. See the below code for an illustration.

# creating a list containing only strings
list_1 = ["This", "is", "the", "first", "list", "containing", "only", "strings"]
# creating a function which takes a string as an argument
# and returns the length of the string 
def length(string):
    return len(string)
# customized the sorting of the list using length function 
list_1.sort(key=length)
# displaying the sorted list
print(list_1)

In the above example, we have created a function with the name length that takes the string as an argument and will return the string’s length. This function name has been passed to the key parameter of the sort() method, which makes the sort() method to sort the list by comparing the length of the strings of the list.

Output:

an illustration to the key parameter of the sort() method
an illustration to the key parameter of the sort() method

Python sorted() function

Python also has a built-in function called sorted() that can be used for sorting python data structures like lists, tuples, etc. This function works almost similar to the sort() method; the main differences are:

  • The sort() method is only used to sort a list, while the sorted() function can be used to sort any data structure, including string, list, tuple, sets, etc.
  • The sort() method does not return anything, while the sorted() function returns a list of the sorted elements.
  • The sort() method performs mutation, which means it directly sorts the original list, which may cause a loss of data if we required the unsorted list too while the sorted() function creates a copy of the list and sort it, then return the new sorted list without affecting the original list.

Syntax:

The syntax of the sorted() function is shown below:

sorted(iterable, key = <function>, reverse = <True/False>)

Parameters:

The sorted function accepts three parameters; one of the parameters is required, and the two are optional. In the sorted() function, note that the required parameter iterable is a positional argument while the others are keyword-only arguments. Let us discuss more details about the arguments.

  • iterable – The sorted() method accepts an iterable in the argument which we want to be sorted. The iterable can be any python iterable object like list, tuple, set, string, etc. This argument is a positional argument, which means that we don’t need to provide the name iterable as we need to do in keyword-only arguments.
  • key – The key parameter is an optional keyword-only parameter that accepts a function name as an argument. This parameter is optional, and the default value for this parameter is None. This parameter is almost similar to the key parameter discussed earlier for the sort() method.
  • reverse – The reverse argument is an optional keyword-only argument. It accepts a boolean value, i.e., either True or False, as an argument. If we provide True as an argument, then the iterable will be sorted in descending order; else, it is sorted in ascending order. The default value of the parameter is False, which means that the list will be sorted in descending order.

Returns:

The sorted() function will return a sorted python list. We can provide any data structure as the argument, and it will always output a python list containing the sorted data. It does not modify the original data structure; it only takes the element of that data structure, sorts them, and puts them into a list.

Examples:

Let us see some examples of how to use the sorted() function to sort a list. The below example shows a list containing some tuples and sorted it using the sorted() function.

# creating a list containing some tuples
list_1 = [(10, 10), (19, 2, 3), (20, 20), (25, 0), (1, 1, 1, 100)]
# sorting the list using default parameters
list_2 = sorted(list_1)
# displaying the sorted list
print(list_2)

In the above code, we first created a list containing some tuples inside it. Then we use the built-in sorted() function of python to sort the list. We provide only the list as the argument, and all other parameters of the sorted() function remain the default.

Output:

A illustration to the key parameter of the sorted function
A illustration to the key parameter of the sorted function

In the output, we can see that the list has been sorted comparing the first element of the tuples. We can also customize the sorting method of the sorted() function by passing a custom function name to the sorted() method. The below example show a simple illustration in which we will sum the elements of each tuple present in the list and sort the list according to the sum of the elements.

# creating a list containing some tuples
list_1 = [(10, 10), (19, 2, 3), (20, 20), (25, 0), (1, 1, 1, 100)]
# creating a function that return the sum of
# the tuple elements in the list
def sum_tup(tup):
    return sum(tup)
# sorting the list using default parameters
list_2 = sorted(list_1, key=sum_tup)
# displaying the sorted list
print(list_2)

In the above code block, we create a function sum_tup() which accepts a tuple as an argument and returns the sum of the elements of the tuple. Then we pass the function name in the key parameter of the sorted() function due to which the sum of the tuple elements is considered during sorting of the list.

Output:

sorting a list using the sorted() function
sorting a list using the sorted() function

On comparing the above output and the output of the previous code block, we can see that in the above output, the sorting is done by comparing the sum of the elements of the tuples present in the list.

Conclusion

In today’s tutorial, we have learned how to sort a list using the sort() method of python lists and the built-in sorted() python function. We have also discussed how we can customize the methods used for sorting by looking at some examples. You may also refer to the tutorial on the various ways in which we can add data into a list.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *