Python instance analysis of the List sorting method

Source: Internet
Author: User

Python instance analysis of the List sorting method

This article describes how to sort the list by Python. Share it with you for your reference. The specific analysis is as follows:

1. sort () function

The sort () function uses a fixed Sorting Algorithm to sort the list. The sort () function changes the original list when sorting the list, so that the elements in the list can be arranged in a certain order, rather than simply returning a copy of the sorted list.

Note that the sort () function changes the original list. The return value of the function is null, that is, None. Therefore, you cannot simply use the sort () function if you need an ordered copy of the list and keep the original list unchanged. To implement the above functions, the sort () method is to first obtain the copy Y of list X and then sort Y. The Code is as follows:

?

1

2

3

4

5

X = [, 4]

Y = x [:]

Y. sort ()

Print x

Print y

The result is as follows:

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

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

Note: Calling x [:] produces shards that contain all elements of x. This is a very efficient way to copy the entire list. It is useless to simply copy x to y through y = x, because this allows both x and y to point to the same list.

2. sorted () function

The sorted () function is used to obtain the sorted list copies. Note that the sorted () function can be used for any iteratable objects.

?

1

2

3

4

X = [, 4]

Y = sorted (x)

Print x

Print y

Result:

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

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

I hope this article will help you with Python programming.

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.