search
HomeBackend DevelopmentPython TutorialPython introduction list.sort method and built-in function sorted

Python introduction list.sort method and built-in function sorted

Related free learning recommendations: python video tutorial

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

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

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

1. list.sort method

The list.sort method sorts the list in place, which means it does not make a 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 in Python: if a function or method changes the object in place, it should return None so that the caller knows the parameters passed in. Changes have occurred and no new objects have been created.

Let’s take a look at the code:

# coding=utf-8
list_a = [1, 2, 8, 3, 7, 9, 5, 7]
# sort()方法没有返回值
list_b = list_a.sort()
print("list_a: ", list_a)
print('list_b: ', list_b)

Running results:

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

Returning None to indicate in-place changes has a drawback to this convention, that is, the caller cannot concatenate it stand up. On the contrary, methods that return a new object can be chained to form a coherent interface.

2. Sorted built-in function

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

This method can accept any form of iterable object as a parameter, even immutable sequences or generators, and regardless of the parameters sorted accepts, it will eventually return a list.

Code example:

list_c = [1, 2, 8, 3, 7, 9, 5, 7]
# sorted内置函数会返回一个排序后的新列表
list_d = sorted(list_c)
print("list_c: ", list_c)
print('list_d: ', list_d)

Running result:

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

It can be seen that when using the built-in function sorted, a new list is returned, but the original list has not changed.

This has two benefits:

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

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

# 可以对非列表的可迭代对象排序生成列表
str_e = 'python'
list_e = sorted(str_e)
print(list_e)

# 链式调用
str_f = '-'.join(sorted(str_e)).upper().split('-')
print(str_f)

Running results:

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

3. Keywords Parameters key and reverse

Whether it is the list.sort method or the sorted function, there are two optional keyword parameters:

key
Receives a function with only one parameter. This function will be used on each element in the sequence, and the result will be the comparison key that the sorting algorithm relies on.

For example, when sorting some strings, you can use key=str.lower to achieve sorting that ignores case, or use key=len to sort based on string length. The default value of key is the identity function, which means that the element's own value is used by default to sort.

reverse:

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

phone = ('HUAWEI', 'OPPO', 'MI', 'MEIZU', 'VIVO')
# 按长度进行排序
phone_list = sorted(phone, key=len)
print(phone_list)

phone_list_re = sorted(phone, key=len, reverse=True)
print(phone_list_re)

Running results:

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

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

If you are careful, you should be able to find that the second result is not a complete flip of the first sorted result.

The lengths of OPPO and VIVO are both 4. After reverse=True, their relative positions are the same as the first sorting. What is the reason for this?

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

Python's sorting algorithm Timsort is stable (just know this), which means that even if the two elements are incomparable in size, their relative positions are fixed in the result of each sort.

Because the sorting algorithm used is stable, that is to say, when the lengths are the same, the relative positions of OPPO and VIVO will not change.

Regarding the use of the list.sort() method and the sorted built-in function, I have now mastered it~

Related free learning recommendations: python tutorial (video)

The above is the detailed content of Python introduction list.sort method and built-in function sorted. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

How are arrays used in image processing with Python?How are arrays used in image processing with Python?May 07, 2025 am 12:04 AM

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

For what types of operations are arrays significantly faster than lists?For what types of operations are arrays significantly faster than lists?May 07, 2025 am 12:01 AM

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft