Sort the elements in the python list | Laptrinhcanban.com

HOME › >>

Sort the elements in the python list

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" ] 
new_list = sorted (list_old)

print ( list_old)
# >> ["C", "A", "B"]

print (new_list)
# >> ["A", "B", "C"]

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"]
mylist.sort()

print(mylist)
#>> ["A", "B", "C"]

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ố
numlist = [84, 75, 92, 90, 78]
newnumlist = sorted(numlist)

print("Before:", numlist)
#>> Before: [84, 75, 92, 90, 78]
print("After: ", newnumlist)
#>> After: [75, 78, 84, 90, 92]
#Sorts a list whose elements
colorlist = ["Blue", "Red", "Green", "White", "Black"]
newcolorlist = sorted(colorlist)

print("Before:", colorlist)
#>> Before: ['Blue', 'Red', 'Green', 'White', 'Black']
print("After: ", newcolorlist)
#>> After: ['Black', 'Blue', 'Green', 'Red', 'White']

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. 
numlist = [ 5 , 3.14 , 4 , 78 , 4 ]

newnumlist = sorted (numlist)
print (newnumlist)
# >> [3.14, 4, 4, 5, 78]

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"]
newmylist = sorted(mylist)

The result returned an error:

Traceback (most recent call last):
File "Main.py", line 2, in <module>
newmylist = sorted(mylist)
TypeError: '<' not supported between instances of 'int' and 'str'

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:


mylist = ["C", "A", "B"]
print(mylist)
#>> ["C", "A", "B"]

# Sort in ascending order
newlist = sorted(mylist)
print(newlist)
#>> ['A', 'B', 'C']

# Sort in descending order
newlist = sorted(mylist, reverse=True)
print(newlist)
#>> ["C", "B", "A"]

Let’s try another more complicated example:

colorlist = ["Blue", "Red", "Green", "White", "Black"]

asc_colorlist = sorted(colorlist)
desc_colorlist = sorted(colorlist, reverse=True)

print("Ordinary list:", colorlist)
#>> Ordinary list: ['Blue', 'Red', 'Green', 'White', 'Black']
print("ascending: ", asc_colorlist)
#>> ascending: ['Black', 'Blue', 'Green', 'Red', 'White']
print("descending :", desc_colorlist)
#>> descending: ['White', 'Red', 'Green', 'Blue', '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"]

sorted(mylist)
#>> ['apple', 'banana', 'desk', 'pen']

sorted(mylist, key=len)
#>> ['pen', 'desk', 'apple', '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]

sorted(mylist)
#>> [-7, -4, 5, 6]

sorted(mylist, key=abs)
#>> [-4, 5, 6, -7]

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"]

sortlist = sorted(animallist)
lowersortlist = sorted(animallist, key=str.lower)

print(animallist)
#>> ['Cat', 'monkey', 'bear', 'Sheep', 'cow']

print(sortlist)
#>> ['Cat', 'Sheep', 'bear', 'cow', 'monkey']

print(lowersortlist)
#>> ['bear', 'Cat', 'cow', 'monkey', 'Sheep']

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']
sorted(a)
print(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

https://laptrinhcanban.com/en/python/nhap-mon-lap-trinh-python/list-trong-python/sap-xep-phan-tu-trong-list-python/

Thank you for reading and please Like & Share for other friends to learn.
">

HOME  › >>

  • Recent Posts
Profile
きよしです!笑

Author: Kiyoshi (Chis Thanh)

Kiyoshi was a former international student in Japan. After graduating from Toyama University in 2017, Kiyoshi is currently working at BrSE in Tokyo, Japan. Kiyoshi là một cựu du học sinh tại Nhật Bản. Sau khi tốt nghiệp đại học Toyama năm 2017, Kiyoshi hiện đang làm BrSE tại Tokyo, Nhật Bản.