SoFunction
Updated on 2025-05-06

Example code of five ways to sort lists in Python

Preface

In Python, sorting is a very common and important operation, especially sorting lists. Python provides a variety of methods to implement sorting operations, from built-in functions to custom sorting logic, it can easily meet different needs. The following will introduce 5 ways to sort lists in Python, accompanied by sample code.

Method 1: Use the sort() method (sort in place)

()is a built-in method for lists that will sort the list itself directly (i.e. sort it in place and will not return a new list). It supports two optional parameters:

  • key: Specify the basis for sorting (usually a function).
  • reverse: Whether to descend, the default value isFalse

Features:

  • Modify the original list, no return value.
  • High efficiency, suitable for handling larger lists.

Sample code:

# Example 1: Default ascending order sortnums = [5, 2, 9, 1, 5, 6]
()  # Sort in placeprint(nums)  # Output: [1, 2, 5, 5, 6, 9]
# Example 2: Sort in descending ordernums = [5, 2, 9, 1, 5, 6]
(reverse=True)
print(nums)  # Output: [9, 6, 5, 5, 2, 1]
# Example 3: Sort based on string lengthwords = ["apple", "banana", "kiwi", "cherry"]
(key=len)
print(words)  # Output: ['kiwi', 'apple', 'cherry', 'banana']

Method 2: Use the sorted() function (return to the new list)

sorted()is a built-in function for sorting iterable objects. andsort()different,sorted()The original list will not be modified, but a new sorted list will be returned.

Features:

  • Don't change the original list, return to the new list.
  • Suitable for scenarios where the original list needs to be retained.

Sample code:

# Example 1: Default ascending order sortnums = [5, 2, 9, 1, 5, 6]
sorted_nums = sorted(nums)
print(sorted_nums)  # Output: [1, 2, 5, 5, 6, 9]print(nums)         # The original list remains unchanged, output: [5, 2, 9, 1, 5, 6]
# Example 2: Sort in descending ordernums = [5, 2, 9, 1, 5, 6]
sorted_nums = sorted(nums, reverse=True)
print(sorted_nums)  # Output: [9, 6, 5, 5, 2, 1]
# Example 3: Sort based on custom ruleswords = ["apple", "banana", "kiwi", "cherry"]
sorted_words = sorted(words, key=len)
print(sorted_words)  # Output: ['kiwi', 'apple', 'cherry', 'banana']

Method 3: Use lambda expressions for custom sorting

Whether it issort()stillsorted(), can be passedkeyParameters specify the sorting basis. Often used herelambdaExpressions to define custom sorting rules.

Features:

  • High flexibility, sorting rules can be defined according to specific needs.
  • Commonly used in complex sorting scenarios.

Sample code:

# Sort by the second element based on the tupledata = [(1, 3), (4, 1), (2, 2), (3, 4)]
(key=lambda x: x[1])  # Sort by the second element of the tupleprint(data)  # Output: [(4, 1), (2, 2), (1, 3), (3, 4)]
# Sort by the last letter of the stringwords = ["apple", "banana", "kiwi", "cherry"]
sorted_words = sorted(words, key=lambda x: x[-1])  # Sort by the last letter of the wordprint(sorted_words)  # Output: ['banana', 'apple', 'cherry', 'kiwi']

Method 4: Use reverse() method to arrange inverse order

reverse()is a built-in method for lists that reverse the order of elements in a list. It should be noted that it is not a true sort, but rather directly reverses the current order.

Features:

  • Modify the original list and directly reverse the list order.
  • More suitable for already sorted lists.

Sample code:

# Example: Arrange the list in reverse ordernums = [1, 2, 3, 4, 5]
()
print(nums)  # Output: [5, 4, 3, 2, 1]

Method 5: Custom sorting algorithm

When built-insort()orsorted()When the needs cannot be met, you can implement your own sorting algorithm (such as bubble sorting, quick sorting, etc.). The following isBubble sortAs an example.

Features:

  • It is more suitable for learning and understanding the implementation principles of sorting algorithms.
  • In actual development, it is recommended to use built-in sorting methods, which are more efficient.

Sample code: Bubble sort

def bubble_sort(nums):
    n = len(nums)
    for i in range(n):
        for j in range(0, n-i-1):
            if nums[j] > nums[j+1]:  # Comparison of adjacent elements                nums[j], nums[j+1] = nums[j+1], nums[j]  # Switch location
# Test codenums = [5, 2, 9, 1, 5, 6]
bubble_sort(nums)
print(nums)  # Output: [1, 2, 5, 5, 6, 9]

Summary and comparison

method Applicable scenarios Whether to modify the original list flexibility Performance
sort() Sort in place, no need to save the original list yes Higher Fast (Timsort algorithm)
sorted() Keep the original list and generate a new sorted list no Higher Fast (Timsort algorithm)
lambdaCustom sorting Scenarios that require complex rules sorting Optional Very high Depend onsort()orsorted()
reverse() Simple inverse order yes generally fast
Custom sorting algorithm Learn the sorting principle or special scenario Optional Very high Depend on the implementation algorithm

Best Practice Recommendations

  • Use built-in methodssort()andsorted()It is the preferred method for sorting, with high performance and easy to use, and is suitable for most scenarios.
  • Custom sorting rules:passkeyParameters andlambdaExpressions can easily implement complex sorting logic.
  • Use custom algorithms for special scenarios: When understanding the principles of sorting algorithms or dealing with special needs, you can implement the sorting algorithm yourself, but the performance may not be as good as the built-in method.

Through the above 5 methods, you can easily sort the list to meet various practical needs!

This is the end of this article about five methods of sorting lists in Python. For more related content on Python list sorting methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!