Posted at: https://laptrinhcanban.com/en
Did you know that after creating a list, you can freely sort the elements in the python list in ascending or descending order? Let’s learn how to sort elements in python list through this lesson.
To sort elements in a python list , we need to use a function sortedor method sorted. With these two ways, we will directly sort the values of the elements in the list in ascending or descending order.
Alternatively, you can also use the value of these elements as an argument to an intermediate function, then get the value obtained to perform the element sort.
Sort the elements in the python list
Sort elements in python list with function sorted()
We sorted the element in the python list using sorted() function with the following syntax:
newlist
= sorted ( ordinary_list
, * , key = None
, reverse = False
)
You can also omit an argument and just use the argument ordinary_list
as follows. In fact, this is also the most commonly used spelling when you want to use functions sorted() by default.
newlist
= sorted ( ordinary_list
)
In addition, we can also use sorted() function not only with lists, but also with strings, tuples etc. So you can also replace the argument ordinary_list
with string or tuple or any other data type that contains an element that you need to arrange.
The only thing to notice is, the argument itself specified does not change, list is still list, tuple is still tuple, string is still string. But the result will always be a new list. Please pay attention, do not wonder why put a string of characters to sort that the result returns to list.
To make it easier to understand, let’s see the following example, we will use the function sorted() like this:
list_old = [ "C" , "A" , "B" ] |
You can see, list_old has been rearranged in ascending order, right?
Sort the elements in the python list using the method sort()
If the sort object is a list, in addition to using the function sorted(), you can use the method sort() to reorder one list. The syntax is as simple as below.
list
.sort()
The usage, the sorting results of the method sort() are the same as the function sorted. Take a look at the same example above with the method’s usage sort:
mylist = ["C", "A", "B"] |
As you can see, the results will be the same as when you used the function sorted().
Difference between sorted(list) vs list.sorted in python
Although the results of the two methods are the same, the difference here is:
- The function sorted() does not change ordinary_list but creates a new_list reordered from ordinary_list
- The method sort() is not create a new list but only rearranges the original list itself.
Also need to note more, inherently fuction and method also different in nature and usage. We will clarify this issue in the following article.
In short, you use functions sorted() when you need to create a new object (list). In the event that you don’t need to create a new object, you will use the method sort().
For example
Here, we will see a few examples of how to sort a list with the elements of list are numbers and characters offline.
#Sắp xếp một list có phần tử là số |
#Sorts a list whose elements |
Sorting elements in the python list contains elements of different data types
In the above section, we learned how to sort the elements in a python list, if that list consists of only the same elements, such as numbers, or strings. So when the data types of the elements in the list are different, what do we do?
The answer here is, if the elements in the list are of different datatypes but are still comparable, then we can sort the list as usual with a function sortedor method sort. For example you want to arrange an integer with float or complex number for example. Like the following example:
# Sort list of integers and real numbers. |
But if you want to sort a list of elements of different data types and they cannot be compared, such as strings and numbers, then if you use the function sortedthen the error TypeErrorwill happen as below :
mylist = ["80", 75, 45, "68"] |
The result returned an error:
Traceback (most recent call last): |
Sorts the elements in the python list in ascending or descending order
By default, the function sorted() or method sort() will sort the list in ascending order. So if you want to sort the elements in the python list in ascending order, then you write the function and method by default as Kiyoshi showed above.
If you want to change the sort order to descending, write the function with the following syntax:
new_list
= sorted ( ordinary_list
, reverse = True
)
The difference here is that we need to specify the value reverse
from the default value False
to True
.
Let’s see the following example:
|
Let’s try another more complicated example:
colorlist = ["Blue", "Red", "Green", "White", "Black"] |
Sorts the element in the python list using an intermediate function
In the previous section, we learned how to sort the elements using directly the values of the elements in the list. In addition to this way, we can also use the value of these elements as an argument to another function, then get the value to perform the element sort.
This is especially useful when you want to decide how to sort your list not based on the value of the element, but on the length of the string that makes up the element, the absolute value of the element, etc.
The syntax in this case is as follows:
newlist
= sorted ( ordinary_list
, key
= function
)
In it, we can use function names like abs
, len
etc.
Let’s see the example below:
Sorts the element in the python list according to the length of the string that makes up the element in the string
We’ll specify the function name to use len: the function that finds the length of the string that makes up the element in the list.
You can refer to len function to find the length of List python
mylist = ["apple", "pen", "desk", "banana"] |
Sorts the element in the python list according to the absolute value of the element in the string
We need to specify the function name to use abs
: the function to give the absolute value, like in the following example:
mylist = [5, -4, -7, 6] |
Sorts the element in the python list by the value converted to lowercase of the element in the string
We need to specify the function name to use str.lower
: the function converts a string to lowercase, like in the following example:
animallist = ["Cat", "monkey", "bear", "Sheep", "cow"] |
Disadvantages of sorting using functions sortedor methodssort
Although these two methods are very easy to use and can be correctly arranged in most cases, in some cases the function sorted() or method sort() may not be able to produce the most natural sort results, like in the example. down here:
a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] |
The result we want is:
['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] |
However, as in the above example, the function has sortednot given the desired result.
In this case, we need to use another function which was not built in when you install python, that is natsort- hàm sắp xếp tự nhiên. This function is not integrated by default when you install python or use python on Anaconda , but you need to install it with the command pip install natsort
, then import
it . We will learn about this function in another lesson.
Summarize
Above, Kiyoshi showed you how to sort the elements in the python list. To better understand the lesson content, practice rewriting today’s examples.
And let’s learn more about Python in the next lessons.
URL Link
HOME › python for beginners>>list in python