An example analysis of how Python sorts lists

Source: Internet
Author: User
Tags sort sorts

The examples in this article describe how Python sorts lists. Share to everyone for your reference. The specific analysis is as follows:

1, sort () function

The sort () function sorts the list using a fixed sort algorithm. The sort () function changes the list as it is sorted so that the elements in the list are ordered in a certain order, rather than simply returning a sorted copy of the list.

Note that the sort () function changes the original list, and the function return value is either null or none. Therefore, if you need a sorted copy of the list, and you want to keep the original list unchanged, you cannot simply use the sort () function directly. The way to use sort () in order to do this is to get the copy y of the list x before sorting Y. The code is as follows:

?

1 2 3 4 5 x=[4,6,2,1,7,9,4] y=x[:] Y.sort () print x print y

The results are as follows:

[4, 6, 2, 1, 7, 9, 4]

[1, 2, 4, 4, 6, 7, 9]

Description: Call x[:] Get a fragment that contains all the elements of X, which is a very efficient way to replicate the entire list. It is no use simply to copy X to Y by y=x, because doing so will let both X and Y point to the same list.

2, sorted () function

Another way to get a sorted list copy is to use the sorted () function. Note that the sorted () function can be used for any object that can be iterated.

?

1 2 3 4 x=[4,6,2,1,7,9,4] y=sorted (x) print x print y

Results:

[4, 6, 2, 1, 7, 9, 4]

[1, 2, 4, 4, 6, 7, 9]

I hope this article will help you with your Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.