Python list sorting list. sort method and built in function sorted usage

  • 2021-10-11 19:03:46
  • OfStack

Many times when we get a list, this list does not meet our needs. What we need is a list with a special order.

At this time, you can use list. sort method and built-in function sorted. This article introduces the use and difference between list. sort method and sorted built-in function.

1. list. sort method

The list. sort method sorts the list in place, which means it does not make a single copy of the original list. This is why the return value of this method is None, reminding you that this method will not create a new list.

Returning None in this case is actually a convention of Python: If a function or method makes in-place changes to an object, it should return None, so that the caller knows that the passed parameters have changed and no new objects have been generated.

Look at the code under 1:


# coding=utf-8
list_a = [1, 2, 8, 3, 7, 9, 5, 7]
# sort() Method has no return value 
list_b = list_a.sort()
print("list_a: ", list_a)
print('list_b: ', list_b)

Run results:


list_a: [1, 2, 3, 5, 7, 7, 8, 9]
list_b: None

One drawback to the convention of returning None to indicate in-place changes is that the caller cannot concatenate them. Methods that return a new object, on the other hand, can be called in a chain to form a coherent interface.

2. sorted built-in functions

Contrary to list. sort, the built-in function sorted creates a new list as the return value.

This method can accept any form of iterative object as a parameter, even an immutable sequence or generator, and no matter what parameters sorted accepts, it will eventually return a list.

Code example:


list_c = [1, 2, 8, 3, 7, 9, 5, 7]
# sorted Built-in functions return 1 New sorted list 
list_d = sorted(list_c)
print("list_c: ", list_c)
print('list_d: ', list_d)

Run results:


list_c: [1, 2, 8, 3, 7, 9, 5, 7]
list_d: [1, 2, 3, 5, 7, 7, 8, 9]

As you can see, when you use the built-in function sorted, a new list is returned, but the original list has not changed.

This has two advantages:

1. If we need to use both the original list and the sorted list, or if we want to sort a non-list iterable object into a list, sorted can do both

2. When there is a return value, we can make a chain call


#  You can sort non-list iterative objects to generate a list 
str_e = 'python'
list_e = sorted(str_e)
print(list_e)
 
#  Chain call 
str_f = '-'.join(sorted(str_e)).upper().split('-')
print(str_f)

Run results:


['h', 'n', 'o', 'p', 't', 'y']
['H', 'N', 'O', 'P', 'T', 'Y']

3. Keyword parameters key and reverse

Both the list. sort method and the sorted function have two optional keyword parameters:

key:

Receive a function with only one argument, which will be used on every one element in the sequence, and the result will be the comparison keyword that the sorting algorithm depends on.

For example, when sorting a few strings, you can use key=str. lower to sort without case, or key=len to sort based on string length. The default value of key is an identity function, which means that the elements are sorted by their own values by default.

reverse:

If set to True, the elements in the sorted sequence are output in descending order (that is, the maximum value is sorted as the minimum value), and the default value of reverse is False.


phone = ('HUAWEI', 'OPPO', 'MI', 'MEIZU', 'VIVO')
#  Sort by length 
phone_list = sorted(phone, key=len)
print(phone_list)
 
phone_list_re = sorted(phone, key=len, reverse=True)
print(phone_list_re)

Run results:


['MI', 'OPPO', 'VIVO', 'MEIZU', 'HUAWEI']
['HUAWEI', 'MEIZU', 'OPPO', 'VIVO', 'MI']

In the above code, the first sort creates a new list of strings sorted by length. The second sort is to change the sort by length from ascending to descending.

Careful you should be able to find that the second result is not a complete flip of the first sorting result.

The length of OPPO and VIVO are both 4, and when reverse = True, their relative position is the same as that of the first order. What is the reason for this?

The sorting algorithm behind sorted and list. sort is Timsort, which is an adaptive algorithm, which alternately uses insert sorting and merge sorting according to the order characteristics of original data to achieve the best efficiency.

Python's sorting algorithm Timsort is stable (just know this 1 point), which means that even if two elements can't compare their sizes, their relative positions are fixed in each sorting result.

Because the sorting algorithm used is stable, that is to say, the relative position of OPPO and VIVO will not change when the length is 1 sample.

With regard to the use of the list. sort () method and the sorted built-in functions, you have now mastered ~

Add: python knowledge points, list sorting sort () and sorted () difference?

sort () is a list-type method that applies only to lists; sorted () is a built-in function that supports various container types. They can all be sorted and used similarly, but sort () is sorted in place and does not return the sorted list, whereas sorted () returns the newly sorted list.


>>> help(list.sort)
Help on method_descriptor:
sort(...)
 L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
 Return a new list containing all items from the iterable in ascending order.
 A custom key function can be supplied to customize the sort order, and the
 reverse flag can be set to request the result in descending order.

This article only briefly introduces the usage of sorting.

For example, the list L:


>>> L = ['python', 'shell', 'Perl', 'Go', 'PHP']

Use sort () and sorted () to sort L. Note that sort () sorts L directly in place, and does not reflect the sorting result by returning values, so there is no need to assign values to variables. sorted () returns the new result after sorting, which needs to be assigned to a variable to save the sorting result.


list_a: [1, 2, 3, 5, 7, 7, 8, 9]
list_b: None
0

It is not difficult to find that sort () and sorted () are both sorted in ascending order by default (A < B < ... < Z < a < b < ... < z). They can all specify the parameter reverse=True to indicate order inversion, which means descending by default:


list_a: [1, 2, 3, 5, 7, 7, 8, 9]
list_b: None
1

In python 3. x, sort () and sorted () do not allow sorting of lists containing different data types. That is, if there are both numeric values and strings in the list, the sort operation reports an error.

The other parameter of sort () and sorted () is key, which defaults to key=None, and this parameter is used to specify a custom sort function to implement the collation you need.

For example, the list above is no longer sorted by the default character order, but rather by the length of the string. So, customize this sort function:


list_a: [1, 2, 3, 5, 7, 7, 8, 9]
list_b: None
2

sort () or sorted () is then called by specifying the parameters of key = sortByLen, during which reverse = True can also be specified:


>>> L = ['shell', 'python', 'Perl', 'PHP', 'Go']
>>> sorted(L,key=sortByLen)
['Go', 'PHP', 'Perl', 'shell', 'python']
5
>>> L.sort(key=sortByLen,reverse=True)
>>> L
['python', 'shell', 'Perl', 'PHP', 'Go']

For another example, sort by the second character of each element in the list.


list_a: [1, 2, 3, 5, 7, 7, 8, 9]
list_b: None
4

More sorting methods, such as specifying two sorting basis, one in ascending order of string length, and the same length in descending order of the second character. The usage is actually very simple, but it takes up a little space, so this article will not explain it.


Related articles: