Sorting is a technique to rearrange the elements or data either in ascending order or descending order. In Python programming, we can do sorting very easily with the help of the methods sort () and sorted ().
The sorted () and sort () methods arrange the elements either in ascending or descending order. Even both perform the same operations, but still, they are different.
For these tutorials, users must have some basic ideas about the list, tuples, and sets. We will be using some basic operations of these data structures to show a clear picture of sort () and sorted () built-in methods. And for this, I am using Python3, so if you are using Python2, then there might be some output difference.
The syntax for the sorted () function is:
We are going to implement sorting on both the string and integer data using the sorted () built-in method.
The sorted () function will accept an iterable and return the sorted iterable elements, which will be in ascending order by default. By default, the sorted () function arranges elements in ascending order because the reverse=False.
In cell number : We created a numeric list of name numbers.
In cell number : We called the sorted () function and passed the numeric list (numbers) into that. We got the sorted list in return, which is also a new list. The new list means that the original list we passed into the sorted () as a parameter is unchanged. From the cell number , we confirm that the original list is unchanged even after the sorted () applies.
The sorted () function has the following properties:
- The sorted () function no need to be defined before use. We can call it directly as we did in the above example (cell number ).
- The sorted () function will do by default ascending order data arrangements if we do not pass any parameters into that.
- The sorted () function returns a new list, which means the original list unchanged, as shown in the above example cell number .
We can also assign the sorted () results back to a new variable as shown below:
In cell number : We created a numeric list of name numbers. We called the sorted () function and passed the numeric list (numbers) into that.
Then we assigned the result of the sorted () function to a new variable sort_results for further use.
Apply sorted () on tuples and sets:
The sorted () function also works on tuples and sets to sort the elements.
In cell number : We created a tuple (num_tuple) and set (num_sets).
In cell number : We called the sorted function and assigned the return results to new variables (tuple_sorted and set_sorted). We then printed the results and got the sorted data. But the results are in the list format, not in the tuples and sets format as we passed the parameters because, by default, the sorted returns the results in list format. So, if we want to get the results in the same format (sets and tuples), we have to use a cast.
In cell number : We can see from the output, now results in the format of the tuple and set as we expected because while calling to the sorted () function, we also applied the cast operator, which converts the list back to the required format.
Now, we are going to apply the sorted () function on the list of strings, as shown below. You will see that before passing the string to the sorted () function, we use the split () method which default format parameter is space (split by space). The reason behind that is to get the whole string as a list but split the whole string when space comes. If we do not do as below, then the whole string will be split character-wise and will not get the correct output as we desire.
So, if we do not use the split () method during the string sorted (), we will get the results like below:
You can see that the whole string when we passed to the sorted () function, returns the list of characters. Now the results are not according to our requirements.
So to overcome this problem, we have to split () the string as shown below. We are splitting the string here with space because we have a space major character that separates the strings. But it’s not a restriction; you can use any formatter inside the split () method according to your string positions.
In Cell number : We initialize a string and then split that string from the space as a split formatter. And we get the list of each string of the whole string instead of the characters of the string.
In cell number : We call the sorted () function and pass that str_value_list as a parameter into that.
In cell number : We finally print the sorted string list returns by the sorted () function. In the cell , we again print the original list to confirm the original list is not changed by the sorted () function.
Sorting with the reverse = True Argument
Now, we will change the default parameter of the sorted () function from False to True. When we change the value of the reverse from False to True, then the sorted () function will sort the data in descending order.
In cell : We created an integer list of name numbers.
In cell : We pass the list (numbers) to the sorted () function. Along with that, we changed the reverse = True. Because of the reverse = True, we got the data in descending order.
In cell : We print the original list to confirm that it has not changed the original list.
Sorting the string case matters
The python uses the Unicode Code to determine the first character of the string before sorting either descending or ascending order. So that, the sorted () function will treat the small case and capital case characters different even though the same, like A or a value, will be different as shown below:
So, to understand this, we again write a small string sorting program.
In cell : We created a string name list with all first character capital.
In cell : When we sorted the names_case, we got the desired result.
In cell : When we change the first character of Harman to harman and Apple to apple and again sort the list, we got an unexpected result because the result shows that the apple string at the 3rd position in the list which actually should be at position 1st in the list index. This is done because of the Unicode code that python used to check their value.
In cell : We print the first character name with their value.
sorted () using the key parameter
The sorted () function has a more powerful feature which is the key argument. This key expects a function, and every element in the list must pass to this key before generating the final output.
We can understand this from this basic example of string sorting. In the previous, we found that python used the Unicode method to determine the first character value, and then, according to that, it sorts the elements. We can overcome this by using the key features, and our result will be according to our expectations.
Now, we can see that from the result, even if the first character is small or capital, we are getting results according to our expectation because the key which we pass convert each element to a small case before going to the sorting. Still, the original value will be printed as we have seen.
Sort () Function
The syntax of the sort () function is
The main difference between the sort () and sorted () function is:
In cell , we can see that the sort () method is a part of the list and not a built-in method. The sort () method also does not work with tuples and sets. The sort () method only works with the list as it is a part of the list class.
We created a new list and called the sort () method as we are calling the sorted (), but we got an error because, as we said before, it’s not a built-in method.
We can call this only using the list with the dot operator as shown above in the syntax.
So we again call the sort () method with the list (numbers), and our data got arranged in ascending order as by default reverse = False. But when we print the original list in cell number , we found that the original list also changed because the sort () method does not return an iterable.
So, we have studied the sort () and sorted () methods. We have also seen that the sort () method is not a built-in method because it’s a list class and can only access the list object. But the sorted () method is built-in and can also work with the tuple and sets.